4ms 1 line c++ solution


  • 12
    L
     int hammingWeight(uint32_t n) {
        return n == 0 ? 0 : 1 + hammingWeight(n & (n - 1));
    }

  • 0
    Z

    Could you please explain what does n & (n - 1) do? Thanks!!


  • 0
    M

    Cannot believe that recursion is actually faster than doing the loop.
    Would you explain that why this is faster than simply doing a while loop(which I got 8ms)?


Log in to reply
 

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