N & (n-1): The lowest bit of 1 in N is changed to 0.
Power of
Given an integer, write a function to determine if it is a power of.
Solution: 2 of the power of the characteristics of a and only one is 1, the rest is zero. It can be used to judge whether N & (n-1) is zero to determine whether N is a power of 2.
Public class Solution { publicboolean ispoweroftwo (int n) { return (n > 0) && ((N & (n-1)) = = 0);} }
Number of 1 Bits
Write a function that takes an unsigned integer and returns the number of ' 1 ' bits it has (also known as the Hamming weigh T).
For example, the 32-bit integer ' One ' 00000000000000000000000000001011 has a binary representation, so the function should return 3.
Solution: The number of 1 is judged according to the number of executions of N & (n-1) until it is 0.
Public class Solution { // need to treat N as a unsigned valuepublic int ham Mingweight (int n) { int result = 0; while (n! = 0) { result+ + ; &= (n-1); } return result;} }
There is also a solution:
Public class Solution { // need to treat N as a unsigned valuepublic int ham Mingweight (int n) { int result = 0; while (n! = 0) {+ = n & 1; >>>= 1; } return result;} }
Bitwise and of Numbers Range
Given a range [M, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, Inclus Ive.
For example, given the range [5, 7], and you should return 4.
The goal of the subject is to have the same number of digits from the highest position of M and n unchanged, and the first number of different bits begin to change to 0.
Solution One: Find the low in the 1, will be 1 0.
Public class Solution { publicint rangebitwiseand (intint n) { while (n > m) { &= (n-1); } return n; }}
Solution Two: The iteration in turn will be low position 0.
Public class Solution { publicint rangebitwiseand (intint n) { if (m = = N) {return m ; } if (m = = n-1) {return m & n ; } return Rangebitwiseand (M/2, N/2) << 1;} }
Bit arithmetic problem