將整數翻轉輸出

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.

有人用一個long long型存貯中間結果。http://www.2cto.com/kf/201501/370484.html

當輸入爲 INT_MIN時,由計算機補碼錶示可知,如果在32位的機器上

INT_MIN的二進制碼爲 10000000 00000000 00000000 00000000

很多人肯定忽視了一個細節 當 取INT_MIN的反數時 並不能取到 2147483648(2的32次方)

因爲計算機在進行 x=-x運算時,在計算機中進行的 補碼的乘法運算 -1的補碼爲 原碼除符號位外 取反加1

-1的源碼 10000000 00000000 00000000 00000001 取反加一變爲了 11111111 11111111 11111111 11111111

所以當 補碼乘法 10000000 00000000 00000000 00000000* 11111111 11111111 11111111 11111111 明顯將溢出的部分捨棄剩餘的就是

10000000 00000000 00000000 00000000也就是 INT_MIN咯 x=-x 不僅僅0成立 在有限位機器上 INT_MIN也成立了

class Solution {
public:
    int reverse(int x) {
        
        bool negative_flag=false;//是否爲負數
        if(x==INT_MIN)   //這裏必須要判斷   應爲 INT_MIN  爲了表示方便用八位 二進制爲 1000 0000  進行x=-x運算時,計算機中用補碼相乘,-1的補碼爲原碼除符號位外取反加1  也就是 1000 0001  取反加一補碼變爲 1111 1111,所以x=-x變爲補碼乘法 1000 0000*1111 1111 =1000 0000,x又等於了INT_MIN ,所以當while循環中的x並沒有爲正數。
        return 0;
        if(x<0)
        {
            x=-x;
            negative_flag=true;
        }
        long long result=0;
        while(x!=0)
        {
            result=result*10+x%10;
            x=x/10;
        }
        if(result>INT_MAX)
            return 0;
        if(negative_flag)
            return -result;
         else
             return result;  
    }
};



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