Java solution, no need to iterate all 32 bits all the time


  • 17
    J

    No need to iterate all 32 bits all the time, for the example provided, only 4 iterations required.

    public int hammingWeight(int n) {
            int result = 0;
            while (n != 0) {
                if ((n & 1) == 1) {
                    result++;
                }
                n >>>= 1;
            }
            return result;
        }

  • 0
    D

    what's the different between

    if ((n & 1) == 1) {
        result++;
    }
    n >>>= 1;
    

    vs

    n = n & (n - 1)
    count++
    

    ?


  • 0
    S
    public int hammingWeight(int n) {
            return n == 0 || n == 1 ? n : (n & 1) + hammingWeight(n>>>1);
    }

  • 0
    D

    In average second approach works works faster.
    Ex: n = 9;
    With first approach you need 4 iterations to count number of bits, while only 2 iterations with second. Hope that helps


Log in to reply
 

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