[7] Reverse Integer

1. 题目描述

Reverse digits of an integer.

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

click to show spoilers.
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer’s last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

翻转一个整数(不包含符号位),如果翻转后这个数字越界则返回0。

2. 解题思路

这个题目和 [9] Palindrome Number这个题目很相似,第9题是需要判断这个数字是否是回文,而这个数字是要求返回求返的数字。这两个题目都涉及了整数求反的问题。他们之间有个共同点就是求的方式是相同的,都是采用前面的结果*10+最后一位的方式求返,不明白可以看题目9中的举例,或者直接看代码。
这个题目需要注意的一点就是,求返数字会越界的问题。当求返的数字超过了int的最大值2147483647时,就会变为负数。所以我使用了之前9中的方法,判断是否为负数返回0,但是有一个测试用例没有通过,我分析的可能是他在某种机缘巧合的情况下刚好等于0了,没有被检测出来。所以使用了另一种方式,在他做乘10加尾数之前就对这个数字进行判定,判断他乘10之后会不会越界,如果越界就返回0。

3. Code

public class Solution {
    public int reverse(int x) {
        // 需要注意保留符号位
        int rev = 0;
        int cur = x;
        if(x < 0)
        {
            cur = Math.abs(x);
        }
        while(cur > 0)
        {
            if(rev > Integer.MAX_VALUE/10) return 0;
            rev = rev*10 + cur%10;
            cur/=10;
        }
        if(x < 0) return -rev;
        return rev;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章