The number of 1 in binary, the number of Binary
Given a 32-bit unsigned integer n, evaluate the number of 1 in the n binary representation. For example, if n = 5 (0101), 2, n = 15 (1111) is returned, return 4
1 # include "stdafx. h "2 3 // It may cause an infinite loop. When n is negative, 4 int NumberOf1_Solution1 (int n) 5 {6 int count = 0; 7 while (n) 8 {9 if (n & 1) 10 count ++; 11 n = n> 1; 12 13 // cout + = n & 1; 14 // n >>= 1; 15} 16 return count; 17} 18 19 // The number of cycles equals to the number of digits in the integer binary 20 int NumberOf1_Solution2 (int n) 21 {22 int count = 0; 23 unsigned int flag = 1; 24 while (flag) 25 {26 if (n & flag) 27 count ++; 28 flag = flag <1; 29 // count + = n & flag? 1:0; 30 // flag <= 1; 31} 32 return count; 33} 34 35/* The best way is to round a few Integers to 36 and subtract an integer from 1, after performing an operation with the original integer, the rightmost 1 of the integer is changed to 0. 37 then the binary value of an integer indicates how many times such an operation can be performed as many as 1. 38 */39 int NumberOf1_Solution3 (int n) 40 {41 int count = 0; 42 while (n) 43 {44 n = (n-1) & n; 45 count ++; 46} 47 return count; 48} 49 50 int main () 51 {52 int number; 53 printf ("enter an integer (ctrl + z exit ):"); 54 while (scanf ("% d", & number )! = EOF) 55 {56 if (number> = 0) 57 printf ("Solution1 is: % d \ nSolution2 is: % d \ nSolution3 is: % d \ n ", 58 NumberOf1_Solution1 (number), NumberOf1_Solution2 (number), NumberOf1_Solution3 (number); 59 else // when number <0, 60 printf ("Solution2 is: % d \ nSolution3 is: % d \ n ", NumberOf1_Solution2 (number), NumberOf1_Solution3 (number); 61 62 printf (" enter an integer (ctrl + z exit ): "); 63} 64 return 0; 65}
The calculation result is as follows: