Why I cannot get through this situation:2^32 ?


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

  • 0
    D

    It's because of integer overflow. The number 2^32 as a signed integer is literally 0 so it's cutting out early.


  • 2
    A

    @ermao in java you need to use this operator ">>>" instead of ">>" on unsigned integers. I know its annoying..


  • 0
    E

    @alan28 Thank you! You are correct!

    Use ">>>" to replace ">>", and remove the "n<0" case, then I passed.

    Here's the code.

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

Log in to reply
 

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