How many 1s are there in the binary number representation of an integer
Title description
Given a 32-bit integer n, return the number of 1 in binary form of the integer.
Enter a description:
Enter an integer, representing n, where n is 32 as an integer.
Output description:
Output an integer, representing the number of 1s in the binary expression of n.
Example 1
enter
1
Output
1
Example 2
enter
-2
Output
31
Remarks:
Time complexity O (1) O (1)O ( 1 ) , additional space complexityO (1) O(1)O ( 1 )。
answer:
If enumeration is performed bitwise, 32-bit enumeration is required, which is slightly inefficient. We can only consider the bit of 1, and there are two ways to get the bit of the rightmost 1 in binary:
- n & (n - 1)
- n & (~n + 1)
Both methods can get the rightmost bit of 1 in the binary representation of n, then remove this 1 and continue processing the rest until all 1s are processed.
Code:
#include <cstdio>
using namespace std;
int main(void) {
int n;
scanf("%d", &n);
int num = 0;
while (n) {
++num;
//n &= (n - 1);
n -= n & (~n + 1);
}
return 0 * printf("%d\n", num);
}