Leetcode 7. Reverse Integer

题目描述:翻转整数,当超出32位时返回0.

题目链接:Leetcode 7. Reverse Integer

思路就是转换成字符串,判断是否为正负,然后再转换成数字。
还有一种就是不断除以10,然后另外一个数不断乘以10这样构建,当发现溢出的时候,退出然后返回0.

代码如下

class Solution {
    public int reverse(int x) {
        boolean flag = true;
        int a = x < 0 ? -x : x;
        StringBuffer sb = new StringBuffer();
        sb.append(a);
        String s = sb.reverse().toString();
        if (x < 0) {
            s = "-" + s;
        }
        try {
            return Integer.parseInt(s);
        } catch (NumberFormatException e) {
            return 0;
        }
        
    }
}

参考链接

《Leetcode 7. Reverse Integer》

点赞