Topic:
An integer is stored in memory and outputs the number of 1 in the binary representation of it
Ideas:
To determine the number of 1 in the binary representation of this integer, it is the topic of the [bitwise operation].
The first thought of clever use [1] This number, [1] only the most right one is 1, the other bits are 0;
So, the next thing you should think of, with "1" and this integer to do [and operations], first of all, you can determine whether the rightmost bit is 1, and so on, the integer every right to move one bit, and 1 to do with the operation, Until the integer becomes 0. At this point, the problem of thinking has been, but consider the abnormal numbers, such as [negative], the method does not apply, because the negative binary needs to maintain the highest bit has been 1, and finally into the Dead Loop (OXFFFFFFFF) in front of the train of thought, two numbers and operations, that can let [1] left shift And the original integer does not move, so you can determine whether the secondary high is 1. With this [1] continue to move left.
There is another way of thinking, a not 0 integer i, at least one is 1, do such an operation:
The result of the i-1 is that the right side of the rightmost 1 of the integer I is all 0 of the bits are changed to 0, that is, after minus 1, all the bits after the rightmost 1 are reversed, and then I do the operation with it, and the result is that all the bits after the rightmost 1 are changed to 0, so, repeating such steps, How many times minus 1 of the operation, I of the binary representation of how many 1, until the number of times minus 1 I becomes 0.
Another: Clear the right-most 0 method:
i=i* (i-1)
How many of the binary representations of an integer are 1