LeetCode 191. Number of 1 Bits

Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).

For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.

题意:给定一个无符号整型,返回该整型的二进制形式中‘1’的个数。
例:‘11’的32位无符号二进制形式为:00000000000000000000000000001011,一共有3个‘1’,因此返回3.

想到了使用java中的位运算来解决,但是没想出来具体怎么使用位运算,对位运算还是不熟悉,然后看了LeetCode提供的参考答案

方法一:逐个检查n的32位无符号二进制形式中的每一位,如果某一位为1,则计数器加1.
令mark=1,1的二进制形式为:0000 0000 0000 0000 0000 0000 0000 0001
将数字n与mark进行与运算,显然,如果n的二进制形式中最后一位是1,则n & mark = 1,否则n & mark = 0.
若n & mark = 1,则将计数器加1.
然后将mark左移一位,检查n的二进制形式中的倒数第二位是否为1。
依次循环,逐个检查n的32位二进制形式中的每一位。

public int hammingWeight(int n) {
        int bits = 0;
        int mark = 1;
        for(int i = 0; i < 32; i++){
            if((n & mark) != 0)
                bits++;
            mark <<= 1;//mark = mark << 1;
        }
        return bits;
    }

方法二:
关于n & (n - 1):
假设n的二进制为:1101011000,
则n-1的二进制为:1101010111,
           n&(n-1)=1101010000
n和n-1的低位不一样,直到有个转折点,就是借位的那个点,从这个点开始的高位,n和n-1都一样。
因此n&(n-1)实际上相当于把n最右边的1消掉了,
所以消掉几次就有几个1.

public int hammingWeight(int n) {
        int bits = 0;
        while(n != 0){
            bits++;
            n &= (n - 1);//n = n & (n - 1);
        }
        return bits;
    }

 参考:https://leetcode.com/problems/number-of-1-bits/solution/

原文地址:https://www.cnblogs.com/zeroingToOne/p/8534463.html