1. 程式人生 > >[LeetCode 7]Reverse Integer(處理整數溢位)

[LeetCode 7]Reverse Integer(處理整數溢位)

題目內容

7.Reverse Interger
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.

Update (2014-11-10):
Test cases had been added to test the overflow behavior.

問題來源

問題簡述

翻轉一個整數

題目分析

翻轉整數時使用變數迭代是一個較為簡單的方法,即按照從低位到高位的順序,對於整數的每一位維護一個變數,每次將該變數乘以十並加上該位數字。關鍵在於根據題目的提示在返回結果前加上對於結果溢位情況下的討論。由此,在定義結果變數是應將其表示範圍定義得更大一些,便於處理該情況。

程式碼示例

#include<limits.h>
class Solution {
public:
    int reverse(int x) {
        long long sum = 0; 
        while(x != 0)
        {
            int
temp = x % 10; sum = sum * 10 + temp; x/=10; } if (sum>INT_MAX||sum<INT_MIN) return 0; return (int)sum; } };