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

posted @ 2020-03-27 21:03  超级学渣渣  阅读(123)  评论(0编辑  收藏  举报