C++ Accepted Easy to understand


  • 0
    W

    Use the approach in 190. Reverse Bits
    First shift mask left then right to get each bit in each iteration
    then check whether the obtained bit is 1.

    class Solution {
    public:
        int hammingWeight(uint32_t n) {
            uint32_t mask;
            int count = 0;
            for(int i = 31; i >=0; i--){
                mask = n;
                mask <<= i;
                mask >>= 31;
                if(mask == 1) count++;
            }
            return count;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.