Share my two C++ solutions


  • 0
    V

    Solution (1):

    class Solution {
    public:
        int hammingWeight(uint32_t n) {
            int ret = 0, i = 0;
            
            for (i = 0; i < 32; i++)
            {
                ret += (n & 1);
                n = n >> 1;
            }
            
            return ret;
        }
    };
    

    or

    class Solution {
    public:
        int hammingWeight(uint32_t n) {
            int ret  = 0, i = 0;
            
            for (i = 0; i < 32; i++)
                if ((n & (1 << i)) > 0)
                    ++ret;
    
            return ret;
        }
    };
    

    Solution (2):

    class Solution {
    public:
        int hammingWeight(uint32_t n) {
            int ret = 0;
            
            while (n > 0)
            {
                if (n % 2 == 1)
                    ++ret;
                n /= 2;
            }
            
            return ret;
        }
    };

Log in to reply
 

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