把一个 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; } }
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int num = in.nextInt(); /* * 将输入的数num与1做&运算,这样会取到num二进制的 * 的最后一位(0或1),之后将num右移一位,与1做&运算后会取到num的第二位 * 依次类推就能得出num每一位上的1 * * eg: * 101 & 001 = 001 count == 0 + 1 * 101 >>> 1 = 010 * 010 & 001 = 000 count == 1 + 0 * 010 >>> 1 = 001 * 001 & 001 = 001 count == 1 + 1 * */ int count = 0; while (num > 0) { count += num & 1; num = num >>> 1; } System.out.print(count); } }