位运算-求一个无符号二进制数中有多少个1

101 阅读1分钟

这里聊一下lowbit,见名知意。就是算一个无符号数最后一个1的位置,其原理就是X&-X,因为计算机中数字是以补码的形式存储,又因为负数的补码是负数绝对值取反加一,因此上面的式子又可得x&(~x+1),这样就能分离出最后一个1了。

比如说

x = 00001010
~x = 11110101
~x + 1 = 11110110
x&(~x+1) = 00000010

所以就得出最后一个1的位置

那么求一个无符号数中有多少个1怎么算呢?

每次减去该数的lowbit数,减到该数为0时,减去的次数就是该数的1的个数。

import java.util.Scanner;

public class _801 {

    public static void main(String[] args) {
        int n = 0, res = 0;
        Scanner scanner = new Scanner(System.in);
        n = Integer.parseInt(scanner.nextLine());
        String[] temp = scanner.nextLine().split(" ");
        int[] array = new int[temp.length];
        for (int i = 0; i < temp.length; i++) {
            array[i] = Integer.parseInt(temp[i]);
        }
        for (int i = 0; i < n; i++) {
            res = 0;
            int tempA = array[i];
            while (tempA != 0){
                tempA -= tempA&-tempA;
                res++;
            }
            System.out.print(res+" ");
        }

    }

}