Question: Implement a function, input an integer, output the number of 1 in the binary representation of the number, eg, 9 is represented as 1001 in binary, and 2 bits are 1, then input 9, the function returns 2
analyze:
Idea 1: First determine whether the rightmost bit in the binary representation of the integer is 1, then shift the input integer to the right by one bit to determine whether the rightmost bit is 1, and move one bit at a time until the entire integer becomes 0
Note: Shifting an integer to the right by one bit is mathematically equivalent to dividing an integer by 2, but the code cannot replace the right shift operation with division by 2, because the efficiency of division is much lower than that of shift operation.
public static int number(int n){ int count=0; while(n!=0){ if((n&1)==1){ count++; } // n=n>>1; when it is negative, it will fall into an infinite loop n=n>>>1;//Unsigned right shift } return count; }
Idea 2: Subtracting an integer by 1 turns the rightmost 1 into 0. If there is still 0 on the right, all 0s become 1 and the left remains unchanged. Next, perform a bitwise AND operation on an integer and the result of subtracting 1 from it, which is equivalent to changing its rightmost 1 to 0. eg: 1100 minus 1 bit 1011, then 1100 and 1011 are combined to get 1000, which is exactly 1100 The result where the rightmost 1 becomes a 0. So the summary is, subtracting 1 from an integer, and then doing AND operation with the original integer will change the rightmost 1 of the integer to 0, then how many 1s there are in the binary representation of an integer, how many times such operations can be performed
public static int numberOfOne(int n){ int count=0; while(n!=0){ count++; n=n&(n-1); } return count; }
By way of inference, related topics:
1. Use a statement to determine whether an integer is an integer power of 2
Analysis: If an integer is an integer power of 2, then only one of its binary representations is 1, and all other bits are 0. So subtract 1 from this integer and then perform an AND operation with itself. This The only 1 in an integer becomes a 0
2. Input two integers m and n, and calculate how many bits in the binary representation of m need to be changed to get n
Analysis: eg, 10 binary is 1010, 13 binary is 1101, it can be seen that the last three digits need to be changed, that is, to find different numbers, that is, you can first find the XOR of these two numbers, and then count the bit of 1 in the XOR demerit. number