1. Title Description
An integer that indicates the number of the output of the binary number 1 in. Wherein a negative number indicates a complement.
2. The ideas and methods
Use Shift (<<) and "|! &" Operation to achieve. Binary 1 is: 0 in front of all, the last one. Every time it shifted to the left, so that the binary representation of the flag is always only one bit is 1, and each n do bits and operation, this is equivalent to individually detect whether each bit of n is 1. unsigned int flag = 1;
3. C ++ core code
3.1 computing
1 class Solution { 2 public: 3 int NumberOf1(int n) { 4 int result = 0; 5 unsigned int flag = 1; 6 while(flag) 7 { 8 if(n&flag) 9 result++; 10 flag = flag<<1; 11 } 12 return result; 13 } 14 };
Reference material
https://blog.csdn.net/qq_28632639/article/details/87966115