topic:
Input an integer and output the number of 1's in the binary representation of the number. Negative numbers are represented in complement.
Ideas:
Obviously, this question examines bit operations.
1. Shift the input number n to the right in turn, and use n&1 to determine whether the last digit is 1;
The problem with this method: if the integer is negative, it will get stuck in an infinite loop. Because when a negative number is shifted to the right, the left side is supplemented by 1, and the integer cannot be 0 during the process of right shifting, so it will fall into an infinite loop.
Two's complement shift:
Shift left, whether positive or negative, add 0 to the right;
Shift right, positive numbers are filled with 0 on the left, and negative numbers are filled with 1 on the left;
code show as below:
class Solution { public: int NumberOf1(int n) { int count=0; while(n){ if(n&1) count++; n=n>>1; } return count; } };
2. Shift 1 to the left by i bits in turn, and then perform the & & operation with the integer. If the result is not 0, the i-th bit is 1;
Question: How many times does an integer have to be looped
code show as below:
class Solution { public: int NumberOf1(int n) { int count = 0; int flag = 1; while( flag ) { if( n & flag ) count++; flag = flag << 1; } return count; } };
3. Use little tricks
Subtract 1 from an integer and then perform a bitwise AND operation with the original integer: n&(n-1) The result is equivalent to changing the rightmost 1 in the binary representation of the integer to 0. Through this little trick, we can count the number of 1s as long as we loop to determine whether n=n&(n-1) is 0.
How many 1s are there in the integer, how many times to loop.
code show as below:
class Solution { public: int NumberOf1(int n) { int count = 0; while( n ) { count++; n = n & (n-1); } return count; } };
4. Bit operation related topics
Using the above techniques, many binary problems can be solved:
- Use a statement to determine whether an integer is a power of 2.
if(n&(n-1)==0) return true;
- Given two integers m, n, how many bits in the binary representation of m need to be changed to get n?
int x=m^n; return NumberOf1(x);