This question has appeared in many tests. I took the test in Alibaba last year and got the test. The beauty of programming is also mentioned. A better method is bit-wise. The solution is as follows:
Execute X & (X-1), set the rightmost 1 to 0, know that the last X is changed to 0, and the cycle ends. The time complexity is O (m ), M is the number of 1 in the binary number.
Another solution is that the time complexity is log (N), where N is the total number of digits of the binary number.
# Include <stdio. h> int main () {unsigned int x = 0 xffffffff; X = (X & 0x55555555) + (x> 1) & 0x55555555 ); // 01010101 x = (X & 0x33333333) + (x> 2) & 0x33333333); // 00110011 x = (X & 0x0f0f0f) + (x> 4) & 0x0f0f0f); // 00001111 x = (X & 0x00ff00ff) + (x> 8) & 0x00ff00ff ); // 0000000011111111 x = x + (x> 16); printf ("% d \ n", X & 0x0000003f); Return 0 ;}
Core Ideas:
The number of bits and bits is counted. The value is stored in the value until it is finally merged into a value, which is the total number of 1.