N & (n-1) purpose, n Server
Recently I did the LeetCode above and found that n & (n-1) is used in many questions ). I think it's really amazing. The following is a summary of some of the current usage:
1. Determine whether the number of an int type is the power of 2.
When n = 4, the binary value is 0100.
N-1 = 3, binary: 0011
Then: n & (n-1) = 0
When n = 8, it is 1000
N-1 = 7, 0111
Then n & (n-1) = 0
Another counterexample: WHEN n = 5, it is 0101.
N-1 is 0100
Then n & (n-1) = 0100 = 4! = 0
From the above we can see that all the power of 2 is a high bit of a binary number of 1, and only this high is 1, such. Then the n-1 value is changed to the high value of 1 to 0, and the remaining low value is changed to 1, for example, 4-, 8-, then n & (n-1) must be 0.
That is, n & (n-1) = 0
2. the number of bits in the binary of a number is 1.
While (n> 0 ){
Count ++;
N = n (n-1 );
}
This principle is a bit similar to the power of 2. You can try it by yourself. The interpretation of the text will never be able to overcome your own practice.
3. Is a number a power of 4?
If a number is a power of 4, it must be a power of 2. Otherwise
Then, first determine the condition n & (n-1) = 0 and determine whether the number is a power of 2. This is a necessary condition.
I just mentioned that a number is a power of 2, but not necessarily a power of 4. For example, 2, 8, and 32 are the power of 2.
However, we can find that the even power of 2, such as 2 ^ 0 = 1 ^ 2 = 4, 2 ^ 4 = 16, these numbers minus 1, can be divisible by 3, 2 cannot be divisible by 3 after the number of odd power minus 1. If you do not believe it, try again.
In this way, we can easily find the necessary and sufficient conditions of the 4 power, that is, n> 0 & (n & (n-1) = 0) & (n-1) % 3 = 0)
4. There are some examples that can use symbols and operations, such as finding a 32-bit binary descending order.
Int result = 0;
For (int I = 0; I <32; I ++ ){
Result <= 1; // The result is first shifted to the left, and the low position is 0.
Result = result + (n & 1 );
N> = 1; // n shifts one digit to the right, and 0 is added to the upper position.
}
5. represent a number in hexadecimal notation and return the corresponding string.
If (n = 0) return "0 ";
String result = "";
String [] map = {"0", "1", "2", "3", "4", "5", "6", "7 ", "8", "9", "a", "B", "c", "d", "e", "f "};
While (n! = 0 ){
Result = map [n & 15] + result;
N> = 4;
}
Okay, so much for the time being. I will try again later.