Description:
第一行輸入數字n(n<=50),表示有n組測試用例,第2到第n+1行每行輸入數m(m為整數),統計並輸出m用二進制表示時,1的個數。
例如:m=9時,二進制表示為1001,則輸出2.
Input:
2
3
7
Output:
2
3
利用位運算
#include <stdio.h> int main() { int binary[20]; int count = 0; int one = 0; int n, i, num; scanf("%d", &n); for (i = 0; i < n; i++) { count = 0; one = 0; scanf("%d", &num); while (num != 0) { binary[count] = num % 2; num /= 2; count++; } for (i = count-1; i >= 0; i--) { if (binary[i] == 1) one++; } printf("%d\n", one); } }
最後通過的代碼:
#include <stdio.h> int main() { int binary[20]; int n, i, num, j; scanf("%d", &n); for (i = 0; i < n; i++) { int count = 0; int one = 0; scanf("%d", &num); while (num != 0) { binary[count] = num % 2; if (binary[count] == 1) { one++; } num /= 2; count++; } printf("%d\n", one); } }
標答:
#include<stdio.h> int bitcount(int x) { int count = 0; while (x != 0) { x &= (x-1); count++; } return count; } int main() { int num; int x; scanf("%d", &num); while (num--) { scanf("%d", &x); printf("%d\n", bitcount(x)); } return 0; }
聽說有一個函數