Finally,I got Accepted !Please notice the boundry case and special cases,-2147483648,1534236469


  • 2
    Y

    I tried many times,that the spcial case 1534236469 couldn`t pass,finally,I change the sum parameter newNum from int to long and accepted.
    Here is my AC code:

    	public static int reverse(int x){
    	long newNum=0,old=x;//*Notice* long,so that it can compare with MAX_Value
    	x=(x>0)?x:(0-x);
    	while(x!=0){
    		newNum*=10;
    		newNum+=x%10;
    		x/=10;
    		if(newNum>Integer.MAX_VALUE||newNum<Integer.MIN_VALUE)
    			return 0;
    	}
    	if(old>0)
    		return (int)newNum;
    	else if(old<0)
    		return (int)(0-newNum);
    	else 
    		return 0;
    		
    }

  • 0
    P

    This is pretty tricky, bug me once, the input type is integer, which is 32-bit signed type, -2147483648 is legal, but the middle result when you calculating a-b<=1, will have overflow.


Log in to reply
 

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