Topic:
Implement a function, enter an integer, and output the number of 1 in the binary representation. As the binary of 9 is 1001, so input 9 output 2.
Solution one: Possible dead loops
int num1 (int n) { int count =0; while (n) { if (n&1) count++; n=n>>1; } return count;}
The above function if you enter a negative number, if you have been doing the right operation, the final figure will become 0xFFFFFFFF and into a dead loop.
Solution Two: No dead cycle but low efficiency
int num1 (int n) { int count =0; unsigned int flag=1; while (flag) { if (n&flag) count++; flag=flag<<1; } return count;}
The number of cycles equals the number of digits in the integer binary, and 32-bit integers need to be looped 32 times.
Solution Three: There are several 1 only need to cycle several times
int num1 (int n) { int count =0; while (n) { ++count; N= (n-1) &n; } return count;}
Sword refers to the number of 1 in offer-binary