将 int 倒转,如:

输入 123,输出 321,

-123、-321,

120、21

如果翻转后 int 越界,就返回 0.

我的解法

public int reverse(int x) {
        if (x == 0) {
            return 0;
        }
        String sx = String.valueOf(x);
        if (sx.length() == 1) {
            return x;
        }
        StringBuilder stringBuilder = new StringBuilder();
        if (x < 0) {
            sx = sx.replaceFirst("-", "");
        }
        char[] chars = sx.toCharArray();
        for (int i = chars.length - 1; i >= 0; i--) {
            char c = chars[i];
            if ("0".equals(c)) {
                continue;
            }
            stringBuilder.append(chars[i]);
        }
        if(x < 0){
            Long l = Long.valueOf("-" + stringBuilder.toString());
            if (l < Integer.MIN_VALUE) {
                return 0;
            }
            return l.intValue();
        }
        Long l = Long.valueOf(stringBuilder.toString());
        if (l > Integer.MAX_VALUE) {
            return 0;
        }
        return Integer.valueOf(stringBuilder.toString());
    }

笨办法,转字符串,然后从后向前读....

官方提供解法

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

好简单.....

这个解法的思路是,将整个数字%10,余数就是最后一位数,然后数字再除10,整个数字就减少了一位。按照输入为 123,上面整段代码就是这个样子:

int x = 123;
System.out.println("pop=" + x%10);
System.out.println("x=" + x/10);
// 0*10 + 3 = 3        
System.out.println("pop=" + 12%10);
System.out.println("x=" + 12/10);
// 3*10 + 2 = 32
System.out.println("pop=" + 1%10);
System.out.println("x=" + 1/10);
// 32*10 + 1 = 321
pop=3
x=12
pop=2
x=1
pop=1
x=0

https://leetcode.com/problems/reverse-integer/