首页 > 代码库 > Reverse Integer Leetcode

Reverse Integer Leetcode

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

这道题要考虑反转之后overflow的问题,感觉我的写法很非主流啊。

public class Solution {
    public int reverse(int x) {
        String str = String.valueOf(x);
        StringBuilder s;
        if (x < 0) {
            s = new StringBuilder(str.substring(1, str.length()));
            s.append("-");
        } else {
            s = new StringBuilder(str);
        }
        str = s.reverse().toString();
        int newX = 0;
        try {
            newX = Integer.valueOf(str);
        } catch(Exception e) {
        }
        
        return newX;
    }
}

还是用主流写法又写了一下

public class Solution {
    public int reverse(int x) {
        long newX = 0;
        while (x != 0) {
            int tmp = x % 10;
            newX = newX * 10 + tmp;
            x = x / 10;
        }
        if (newX > Integer.MAX_VALUE || newX < Integer.MIN_VALUE) {
            return 0;
        }
        return (int) newX;
    }
}

 

Reverse Integer Leetcode