4ms C++ solution


  • 0
    D
    class Solution {
    public:
        int hammingWeight(uint32_t n) {
            if(n>0)
                return n%2==1 ? 1+hammingWeight(n/2) : hammingWeight(n/2);
            else
                return 0;
        }
    };

  • 0
    W

    Why this solution is much faster than the non-recursive solution? I'm confused about it... My solution costs 12ms.

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

Log in to reply
 

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