Try   HackMD

Leetcode 7. Reverse Integer (C語言)

  • 題目
    Given a 32-bit signed integer, reverse digits of an integer.

  • 範例
    Example 1:
    Input: 123
    Output: 321

    Example 2:
    Input: -123
    Output: -321

  • Note:
    Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [\(−2^{31}\), \(2^{31} − 1\)]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

int reverse(int x){ int y=0; while(x!=0){ if(y>INT_MAX/10||y<INT_MIN/10)return 0; else if(y==INT_MAX/10||y==INT_MIN/10){ if(x%10>7||x%10<-8)return 0; } y=y*10+x%10; x/=10; } return y; }

思路:mod(%)可取尾數 搭配除法即可反轉,此題的重點反而在於overflow。
INT_MAX\(=2^{31} − 1=2147483647\),INT_MIN\(=-2^{31}=-2147483648\)

如果某一次while當中y>214748364(INT_MAX/10),那麼乘10後必然會overflow。
同理若y<-214748364(INT_MIN/10)也會overflow。

要是y=INT_MAX/10或INT_MIN/10呢? 就要再看尾數(x%10)有沒有>7或<-8來判斷會不會overflow

若INT_MAX/10>y>INT_MAX/10則必然不會overflow。