4ms C++ algorithm, easy to understand


  • 0
    J

    Let n&1, if the answer is not equal to zero, this means there exists one '1'.
    Then n shift right one bit.
    End the loop until n=0.

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

Log in to reply
 

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