整数反转

109 阅读1分钟

整数反转

说明

给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。

如果反转后整数超过 32 位的有符号整数的范围 [−231,  231 − 1] ,就返回 0。

假设环境不允许存储 64 位整数(有符号或无符号)。

示例 1:

输入:x = 123
输出:321

示例 2:

输入:x = -123
输出:-321

示例 3:

输入:x = 120
输出:21

示例 4:

输入:x = 0
输出:0

提示:

  • -2^31 <= x <= 2^31 - 1

来源:力扣(LeetCode) 链接:leetcode.cn/problems/re…

题解

解法

字符串进行反转

   public static void main(String[] args) {
        System.out.println(demo(-123));
    }

    public static  int demo(int x){
        String str = x + "";
        int sum = -1;
        boolean flag = false;
        if(x < 0){
            flag = true;
            sum++;
        }
        StringBuffer sb = new StringBuffer();
        for (int i = str.length() - 1; i > sum; i--) {
            sb.append(str.charAt(i));
        }
        int parseInt = 0 ;
	//题目要求不能使用64位的整数(有符号和无符号)
        try {
            parseInt = Integer.parseInt(sb.toString());
        }catch (Exception e){
            return 0;
        }
        return flag ? -parseInt : parseInt;
    }