letcode 7 整数反转

整数反转

解法1

if(x==0) return x;
        StringBuilder res=new StringBuilder();
        if(x<0){
            res.append('-');
            x = Math.abs(x);
        }
        while (x>0){
            int a = x%10;
            res.append(a);
            x/=10;
        }

        try{
            return Integer.parseInt(res.toString());
        }catch (Exception e){
            return 0;
        }
View Code

解法2

public static int reverse2(int x) {
        int res = 0;
        while (x != 0) {
            int tmp = x % 10;
            int resTmp = res*10+tmp;
            if((resTmp-tmp)/10!=res) return 0;
            res = res * 10 + tmp;
            x /= 10;

        }
        return res;
    }
View Code

这两种方法执行效率都是2ms

原文地址:https://www.cnblogs.com/superxuezhazha/p/12584341.html