一、基本思路
1、n 的二进制表示中,第 k 位是 1 还是 0
-
- 先把第 k 位移到最后一位—— n >> k
-
- 看个位是 1 还是 0 —— x & 1
2、Lowbit(x):返回 x 的最后一位 1
- 表达式:x & (- x)= x & ( ~x + 1 )
- 补码表示:- x = ~x + 1
- 可以用来统计有多少个 1
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/b853289dbd2011389317f7cd8e0afa7c.png)
二、模板实现
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int N = 1000010;
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] a = new int[N];
for (int i = 0; i < n; i++) {
a[i] = scanner.nextInt();
}
for (int i = 0; i < n; i++) {
int count = 0;
while (a[i] != 0){
count ++;
a[i] -= (a[i] & (~ a[i] + 1));
}
System.out.print(count + " ");
}
}
}
求n的第k位数字: n >> k & 1
返回n的最后一位1:lowbit(n) = n & -n