Super Fast Solution C++


  • 2
    W
    class Solution {
    public:
    int hammingWeight(uint32_t n) {
        int count = 0;
        while (n != 0) {
            count++;
            n &= (n - 1);
        }
        
        return count;
    }
    

    };

    It only takes 10 ms.


  • 0
    O

    Super super fast and short solution in GCC is using the builtin function:

    class Solution {
    public:
    int hammingWeight(uint32_t n) {
      return __builtin_popcount(n);
    }

  • 0
    H

    Er.. is that a algorithm?


Log in to reply
 

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