Readable simple JAVA solution O(1)


  • 31
    C

    In the following solution:

    1. Iterate over 32 bits since its a 32-bit integer. This will be O(1) since it is in constant time
    2. Left shift the number by i to get the LSB value
    3. Do an AND of the number obtained from step 2 with 1. If the result of the AND is 1 then increment the count because the LSB value of that bit was 1.
     public int hammingWeight(int n) {
            int count = 0;
            for(int i=0; i<32; i++){
                count += (n >> i & 1) == 1 ? 1: 0;
            }
            return count;
        }
    
    

  • 1
    H

    @codergal I think step #2 should be "Right shift..." not "Left shift...".


  • 0
    T

    why n&1 will fail?I don't get it.

    rtn += n&1;
    n = n>>1;
    

  • 0

    @codergal
    You can change the solution:

    public int hammingWeight(int n) {
        int count = 0;
        for(int i = 0; i < 32; i++){
            count += (n >> i & 1);
        }
        return count;
    }

Log in to reply
 

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