[leedcode 07]Reverse Integer

public class Solution {
    public int reverse(int x) {
        //此题需要注意整数越界问题,因此先将res声明为long,注意32位的范围是0x80000000到0x7fffffff
        long res=0;
        int flag=1;
        if(x<0) {
            flag=0;
            x=-x;
        }
        while(x>0){
            int temp=x%10;
            res=res*10+temp;
            if(flag==1&&res>0x7fffffff)break;
            if(flag==0&&-res<0x80000000) break;
                
            x=x/10;
        }
        if(x>0)return 0;
        if(flag==0) res=-res;
        return (int)res;
       
        
    }
}

 

你可能感兴趣的:(Integer)