Simple and Straightforward C++ Solution with Explanation.


  • 0
    K
    class Solution {
    public:
        int hammingWeight(uint32_t n) {
            int res=0;
            while(n){
                //Get the lowest bit and add to result. 
                //If it is bit 1, temp will be 1; if it is bit 0, temp will be 0
                int temp=n&1; 
                res+=temp;
                n=n>>1;
            }
            return res;
        }
    };

Log in to reply
 

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