[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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章