Java solution(bitwise operation)


  • 2
    N
    public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        
        int x=1;
        int ans = 0;
        
        for(int i=0 ; i<32 ; i++){ //32bit
            
            if( (n&x) != 0 ) //if the bit is "1"
                ans++;
            
            x=x<<1 ;   
        }
        
        
        return ans ;
    }
    

    }


  • 2
    D

    My other solution:

    public class Solution {
        // you need to treat n as an unsigned value
        public int hammingWeight(int n) {
            int count = 0;
            
            while(n != 0){
                if((n & 1) == 1) count++;
                n >>>= 1;
            }
            return count;
        }
    }

  • 0
    S

    I think the following solution is very straightforward:

    public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
    int x = 0;
    while (n != 0) {
    x++;
    n &= (n-1);
    }
    return x;
    }
    }


Log in to reply
 

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