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 }