leetcode Question: Number of 1 Bits

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.


Analysis:

This is a very basic bit manipulation problem.
In order to count the number of 1 in the bit string, we can use a mask to check if the last bit is 1 or 0.
Cut the last bit (shift 1 bit right) and iterate this operation can achieve the final task.

mask = 1, binary of which is 0000...000001 (length meets with uint32)
shift operation:   >>1.

Note that << shifts left and adds 0s at the right end
>> shifts right and adds 0s at the left (when data is unsigned int)



Code(C++):

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int res=0;
        while (n){
            if (n&1){
                res++;
            }
            n = n>>1;
        }
        return res;
    }
};

Code(Python):

class Solution:
    # @param n, an integer
    # @return an integer
    def hammingWeight(self, n):
        res = 0
        while n:
            if n&1:
                res += 1
            n = n >> 1
        return res
        
        

No comments:

Post a Comment