面试题15 二进制1的个数

自身 & (自身-1) 可以使最低位的1置为0

 Java中int类型的负数的二进制用补码的形式存储

下面算法不适合负数

    public int numberOf1(int num) {
        int count = 0;
        while (num != 0) {
            num = num & (num - 1);
            count++;
        }
        return count;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int a = 60;
        System.out.println(solution.numberOf1(a));
    }

猜你喜欢

转载自www.cnblogs.com/youzoulalala/p/11300249.html