LeetCode7. 反转整数

题目

给定一个 32 位有符号整数,将整数中的数字进行反转。

示例 1:

输入: 123
输出: 321

 示例 2:

输入: -123
输出: -321

示例 3:

输入: 120
输出: 21

注意:

假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231,  231 − 1]。根据这个假设,如果反转后的整数溢出,则返回 0。 

代码

class Solution {
    public int reverse(int x) {
        String xs = "";
        
        if (x < 0 ) xs = Integer.toString(x*-1);
        else if ( x == 0) return 0;
        else xs = Integer.toString(x);
        

        String str = new StringBuffer(xs).reverse().toString();
        
        try{
            int re = Integer.parseInt(str);
            return x<0? -1*re : re;
        }catch (NumberFormatException e){
            return 0;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38595487/article/details/81072987