Java 2ms Solution


  • 3
    R
    public int hammingWeight(int n) {
    		int sum = 0;
    		while(n != 0) {
    			if ((n & 1) == 1) {
    				sum++;
    			}
    			n = n >>> 1;
    		}
    		return sum;
    	}

  • 0
    L

    public int hammingWeight(int n) {

        int count=0;
        while(n!=0){
            if(n%2!=0){
                 count++;
            }
            n=n>>>1;
        }
        return count;
    }

  • 0
    P

    if I do : n = n >> 1; - why this is getting failed for an input 2147483648 (10000000000000000000000000000000)
    So what is the difference between >> and >>> operators?

    Also can you check why the below solution is also failed :
    public int hammingWeight(int n) {

        if(n>Integer.MAX_VALUE || n<=Integer.MIN_VALUE )
            return 0;
    
        int count=0;
        while(n > 0){
           count++;
           n= n & (n-1);
        }
        
        return count;
    }

Log in to reply
 

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