求n的第k位数字
import java.io.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(new InputStreamReader(System.in));
int n = sc.nextInt();
int k = sc.nextInt();
System.out.println(n >> k & 1); //输出n对应的二进制数的第k位
//将n对应的二进制数,从第k位~第0位依次输出
for (int j = k; j >= 0; j--) System.out.print((n >> j & 1)+" ");
}
}
二进制中1的个数
lowbit(x) :返回x的最后一位1
例: x = 1010
lowbit(x) = 10
; x = 101000
lowbit(x) = 1000
实现:
int lowbit(x){
return x & (-x);
}
直接调用Integer类中的bitCount方法