2015年7月30日 星期四

LEET code-Reverse Integer



Reverse digits of an integer.

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

可能會overflow
一開始的寫法想太複雜
還先去算長度
如果長度==10
在去作處理
但是根本只要到 9位數在判斷就好
因為要超過INT_MAX或是INT_MIN的尾數 在還沒反轉之前就會先overflow了
所以第9位在判斷就好






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

沒有留言:

張貼留言