【LeetCode 7: Reverse Integer】

Description:

Reverse digits of an integer.

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

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.

參考代碼:

class Solution {
public:
    int reverse(int x) {
        int ans = 0;
        while(x) {
            if(ans > INT_MAX / 10 || (ans == INT_MAX / 10 && (x%10) > INT_MAX % 10) || 
                ans < INT_MIN / 10 || (ans == INT_MIN/10 && (x%10)<INT_MIN % 10) )
                return 0;
            ans = ans * 10 + x % 10;
            x /= 10;
        }
        return ans;
    }
};

代碼已測試通過

思考與小結:

這道題不要嘗試將輸入的數先轉換位整數再進行運算,因爲可能負數在轉換爲整數的時候就可能發生了溢出,但實際上應得到的結果不應該是溢出是的結果0;因此直接對原數進行操作即可;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章