[LeetCode]整数反转

刚开始想弄一个flag区分正数和负数的,后来发现没这个必要,res的符号始终和原数是一样的。然后用java中Integer类中有MIN_VALUE和MAX_VALUE,用这两个常量来做判断会比较好。处理溢出的时候不要用res*10要用MIN_VALUE/10,防止溢出

问题链接:https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/5/strings/33/

代码:

    public int reverse(int x) {
        int res=0;
        while(x!=0) {
            int temp = x%10;
            if(res>Integer.MAX_VALUE/10||res == Integer.MAX_VALUE/10 && temp>7){
                return 0;
            }
            if(res<Integer.MIN_VALUE/10 || res == Integer.MIN_VALUE/10 && temp<-8){
                return 0;
            }
            res=res*10+temp;
            x=x/10;
        }
        return res;
    }

猜你喜欢

转载自blog.csdn.net/sinat_37273780/article/details/84778270