ReverseInteger:实现int整数的反转

原文链接

Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

class Solution1 {
    public int reverse(int x) {
        while (x % 10 == 0) {
            x /= 10;
        }
        boolean tag = false;
        if (x < 0) {
            tag = true;
            x = x * -1;
        }
        String s = String.valueOf(x);
        char[] ch = s.toCharArray();
        for (int i = 0;i < ch.length;i++) {
            int k = ch.length - i - 1;
            if (k < ch.length / 2) break;
            char cc = ch[i];
            ch[i] = ch[k];
            ch[k] = cc;
        }
        String re = String.valueOf(ch);
        int RI = Integer.valueOf(re);
        if (tag) RI = RI * -1;
        System.out.println(RI);
        return RI;
    }
}
/*
* 1. 前几天刚做了字符反转的,想当然就以为可以直接拿来用。结果却和出题人意图相差甚远.Solution1的方案对于小部分的测试数据可行,但是当前的状态是行不通的,也没有继续对此进行修改完善.
* 2. 一开始做的时候下面的Solution思路类似,但是因为对算法的逻辑思路不是很透彻,写出来的代码肯定很杂乱繁琐。下面的这个解题思路有参考到Discussion中的一个答案.
* 3. 昨晚做出来之后一直不晓得哪里出错了,没有意识到int类型的边界范围,还特别纳闷为啥断点跟踪的时候1534236469这个数字最后一下子就变了.根本没有考虑过怎么处理"int类型数据溢出"问题
*   上网搜索了一下之后才晓得怎么判断int类型问题。https://www.cnblogs.com/hesiyi/p/6963435.html
*
* */
class Solution {
    public int reverse(int x) {
        int sum = 0;
        int t = 0;
        while (x != 0) {
            if ((sum * 10L) > Integer.MAX_VALUE || (sum * 10L) < Integer.MIN_VALUE)
                return 0;
            sum = sum * 10 + x % 10;
            x = x / 10;
        }
        return sum;
    }
}
public class ReverseInteger {
    public static void main(String[] args) {
        Solution1 solu = new Solution1();
        int kkk = solu.reverse(-214748364); // -2147483648,1534236469
        System.out.println(kkk);
    }
}

关于int类型数据溢出的问题,移步博客:java-int数据的溢出

posted @ 2019-03-06 22:56  LeonWen  阅读(1450)  评论(0编辑  收藏  举报