把一个 32-bit 整型转成二进制,其中包含多少个 1 ,比如 5 的二进制表达是 101 ,其中包含 2 个 1
数据范围:输入的数字满足 
#include <stdio.h>
#include <stdlib.h>
int bit_count(int x) {
int n = 0;
while (x) {
x &= x - 1;
++n;
}
return n;
}
int main(const int argc, const char* const argv[]) {
int x;
fscanf(stdin, "%d", &x);
fprintf(stdout, "%d\n", bit_count(x));
return 0;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int i = scanner.nextInt();
String s = Integer.toBinaryString(i);
char[] array = s.toCharArray();
int count=0;
for (char c : array) {
if (c=='1')
count++;
}
System.out.println(count);
}
}
#include <bits/stdc++.h>
using namespace std;
int main() {
int n = 0;
while (cin >> n) {
bitset<32> b(n);
cout << b.count() << endl;
}
return 0;
} import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int digit = Integer.valueOf(sc.nextLine());
int num = getNumOfOne(digit);
System.out.println(num);
}
public static int getNumOfOne(int digit) {
int num = 0;
for (int i = 0; i < 32; i++) {
//例:10011011
// 每次右移一位,判断是否为1
num += digit & 1;
digit >>>= 1;
}
return num;
}
}