Leetcode 7. Reverse Integer

Checking integer overflow and negative number.

class Solution {
    public int reverse(int x) {
        if(x>-10 && x<10){
            return x;
        }
        long res=0;
        int flag=0;
        if(x<0){
            flag=1;
            x=-x;
        }
        while(x!=0){
            res=res*10+x%10; //core 
            x=x/10;
        }
        if(res>=Integer.MAX_VALUE||res<=Integer.MIN_VALUE){
            return 0;
        }
        if(flag==1){
            return -(int)res;
        } 
        return (int)res;     
    }
}

你可能感兴趣的:(leetcode,Math,Only,leetcode,java)