AcWing 801. 二进制中1的个数
原题链接
简单
作者:
ss_uaena
,
2021-12-30 10:37:09
,
所有人可见
,
阅读 184
- 注意:每次求出最后一位1之后,要减去这个数
- 使用c++的话,直接根据位运算的模板即可求出
#include <iostream>
using namespace std;
int lowbit(int x) {
return x & -x;
}
int main() {
int n;
scanf("%d", &n);
while (n--) {
int x, res = 0;
scanf("%d", &x);
while (x) {
x -= lowbit(x);
res++;
}
printf("%d ", res);
}
}
- 使用 Java的话,Java提供了统计二进制个数的方法,直接调用提供的 api 即可,当我们要求一个数 x 对应二进制有多少个1时,只需要把这个数作为参数传入到 Integer.bitcount(x),返回值为 二进制中1的个数。
import java.io.*;
public class Main {
/*
java中把统计二进制个数方法封装在jdk中了,可以直接调用Integer类中的bitCount方法
*/
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] inputStr = br.readLine().split(" ");
int n = Integer.parseInt(inputStr[0]);
inputStr = br.readLine().split(" ");
for (int i = 0; i < n; i++) {
int x = Integer.parseInt(inputStr[i]);
System.out.print(Integer.bitCount(x) + " ");
}
}
}