How to juge overflow without using long in java


  • 0
    L
    public class Solution {
        public int reverse(int x) {
            int result = 0;
            while(x !=0 ){
                int addend = x%10;
                x=x/10;
                result=result*10+addend;
                //next time the result*10 overflow
                if(result>Integer.MAX_VALUE/10 && x!=0 || result<Integer.MIN_VALUE/10 && x!=0)
                    return 0;
                //next time result*10 + x overflow
                else if(result==Integer.MAX_VALUE/10 && x>7 || result==Integer.MIN_VALUE/10 &&x<-8)
                	return 0;
            }
            return result;
        }
    }
    

Log in to reply
 

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