剑指offer——面试题15:二进制中 1的个数
1 // 面试题15:二进制中1的个数 2 // 题目:请实现一个函数,输入一个整数,输出该数二进制表示中1的个数。例如 3 // 把9表示成二进制是1001,有2位是1。因此如果输入9,该函数输出2。 4 5 #include <cstdio> 6 7 int NumberOf1_Solution1(int n) 8 { 9 int count = 0; 10 unsigned int flag = 1; 11 while (flag) 12 { 13 if (n & flag) 14 count++; 15 16 flag = flag << 1; 17 } 18 19 return count; 20 } 21 22 int NumberOf1_Solution2(int n) 23 { 24 int count = 0; 25 26 while (n) 27 { 28 ++count; 29 n = (n - 1) & n; 30 } 31 32 return count; 33 } 34 35 // ====================测试代码==================== 36 void Test(int number, unsigned int expected) 37 { 38 int actual = NumberOf1_Solution1(number); 39 if (actual == expected) 40 printf("Solution1: Test for %p passed.\n", number); 41 else 42 printf("Solution1: Test for %p failed.\n", number); 43 44 actual = NumberOf1_Solution2(number); 45 if (actual == expected) 46 printf("Solution2: Test for %p passed.\n", number); 47 else 48 printf("Solution2: Test for %p failed.\n", number); 49 50 printf("\n"); 51 } 52 53 int main(int argc, char* argv[]) 54 { 55 // 输入0,期待的输出是0 56 Test(0, 0); 57 58 // 输入1,期待的输出是1 59 Test(1, 1); 60 61 // 输入10,期待的输出是2 62 Test(10, 2); 63 64 // 输入0x7FFFFFFF,期待的输出是31 65 Test(0x7FFFFFFF, 31); 66 67 // 输入0xFFFFFFFF(负数),期待的输出是32 68 Test(0xFFFFFFFF, 32); 69 70 // 输入0x80000000(负数),期待的输出是1 71 Test(0x80000000, 1); 72 73 return 0; 74 }