位运算

64 阅读1分钟

模板

求n的二进制下第k位数字

  • n = 15 = (1111)₂
  • 规定二进制下最右一位是第0位
先把第k位移到最后一位:
n >> k;
看个位是几:
x & 1
结合起来:
n >> k & 1

返回n的二进制下的最后一位1

lowbit(n) = n & -n
    
原理:
  x & -x = x & (~x + 1)
       x = 1010……100……0
      ~x = 0101……011……1
    ~x+1 = 0101……100……0
x&(~x+1) = 0000……100……0
最后得到的就是     100……0

练习

01 二进制中1的个数

  • 题目

Snipaste_2023-02-25_22-17-56.png

  • 题解
import java.io.*;

public class Main {
    public static final int N = 100010;
    public static int[] q = new int[N];
    public static int n;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        n = Integer.parseInt(br.readLine());
        String[] str1 = br.readLine().split(" ");
        for (int i = 0; i < n; i++) {
            q[i] = Integer.parseInt(str1[i]);
        }

        for (int i = 0; i < n; i++) {
            int res = 0;
            while (q[i] != 0) {
                q[i] -= lowbit(q[i]);
                res++;
            }
            pw.print(res + " ");
        }
        pw.close();
        br.close();

    }
    public static int lowbit(int a) {
        return a & -a;
    }
}