Title description
Enter an integer, and output the number of 1s in the 32-bit binary representation of the number. The negative number is represented by one's complement.
Example 1
input
10
return value
2
Problem-solving ideas:
Let’s first observe the binary form of a set of numbers:
000 0
001 1
010 2
011 3
100 4
101 5
110 6
111 7
We look at the integer corresponding to this binary, and observe the relationship between the nth number and the n-1th number, and the binary digits:
for example , the binary number of the number 6, the first 1 from the right, and the following 0, and 5 corresponds to binary and 6 corresponds to the number corresponding to the rightmost 1 is inverted, and to the right, the same is true. That is, looking at the first 1 from the right side of the binary of n, the corresponding digit of the binary of n-1 is obtained by inverting n (for example, 6–》10, and 5 corresponds to 01).
From this feature, we can Let n be ANDed with n-1, so that the binary digits starting from the first 1 from the right side will become 0, and the result will be ANDed with the previous digit again. . . This loop until the result of the phase and is equal to 0. Calculate the number of phases and you can know how many 1s are in the binary of n;
Code:
public class Solution {
public int NumberOf1(int n) {
int count=0;
while(n!=0){
count++;
n=n&(n-1);
}
return count;
}
}