题目链接:https://www.acwing.com/problem/content/803/
解法:
核心lowbit操作:x & -x
操作的含义:
- x代表原数(不论负数正数):如101110100
- -x的计算方式是:x的所有位取反+1,即010001011 + 1 = 010001100
- x & -x即为100
总而言之,lowbit操作就是取数字x的首位1之后所有数的方法。
关于原码、反码、补码可以详见这篇博客:
https://www.acwing.com/solution/content/32726/
AC代码:
import java.util.*;
public class Main {
static int lowbit(int x) {
return x & -x;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
while (n -- > 0) {
int x = sc.nextInt();
int cnt = 0;
while (x != 0) {
x -= lowbit(x);
cnt ++;
}
System.out.print(cnt + " ");
}
}
}