LeetCode 第 7 題(Reverse Integer)

liyuanbhu發表於2016-04-17

LeetCode 第 7 題(Reverse Integer)

題目是這樣的:

Reverse digits of an integer.

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

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.

這道題的難度等級被標為 “Easy”, 實際上這道題並不 “Easy”. 難點就在於要考慮整數溢位的問題.

先給個不考慮整數運算溢位問題的程式碼(實際上,一開始寫程式碼就考慮的太全面的話,會很難下筆。這時不如先寫個大概能用的,然後再一步步重構來改善程式碼):

int reverse(int x)
{
    int ret = 0;
    do
    {
        ret = 10 * ret + x % 10;
        x = x / 10;
    }while(x);
    return ret;
}

如何簡便的判斷運算是否溢位是個難題。我暫時還沒找到好辦法。不過解決這個問題可以用些變通的方法。比如說我把 x 的每個十進位制位的具體數字都記錄下來。然後與我算出的結果進行比較,如果對應的位都是對的,那就表示沒有溢位。下面是按照這個思路給出的程式碼。

int reverse(int x)
{
    int ret = 0;
    int count = 0;
    char str[12];
    do
    {
        str[count++] = x % 10;
        ret = 10 * ret + x % 10;
        x = x / 10;
    }while(x);
    int ret2 = ret;
    while(count > 0)
    {
        if( ret % 10 != str[--count])
        {
            return 0;
        }
        ret = ret / 10;
    }
    return ret2;
}

還有另外一種思路,既然用 int 型進行計算會溢位,那就選個更大的資料型別,比如 long long,這樣不就不溢位了。按照這個思路,有下面的程式碼:

int reverse(int x)
{
    long long ret = 0;
    do
    {
        ret = 10 * ret + x % 10;
        x = x / 10;
    }while(x);

    if(ret > INT_MAX || ret < INT_MIN)
    {
        return 0;
    }
    return ret;
}

這個程式碼比較簡潔,對這個問題來說應該是個不錯的答案。

相關文章