How many '1' s are there solutions
Description:
Description:
Input number n (n <= 50) in the first line, indicating that there are n groups of test cases. input number m (m is an integer) in each line from row 2nd to row n + 1 ), count and output the number of 1 in the binary representation of m.
For example, if m = 9, if the binary value is 1001, 2 is output.
Input:
2
3
7
Output:
2
3
Hint:
Bitwise operations
A relatively simple question, which can also have advanced practices. Although bit operations are prompted, bit operations are not used because you are not familiar with bit operations. Wrong code: (the computer manager directly regards it as a spyware and killed it ..) If you do not understand the problem, post it first.
#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); }}
Code passed:
#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); }}
Answer:
#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;}
I heard there is a function.