程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> Reverse Integer leetcode

Reverse Integer leetcode

編輯:C++入門知識

Reverse Integer leetcode


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.

題目的意思是要將一個整數反轉, 當反轉後的數 溢出時返回0

這裡需要注意的是:

當輸入為 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;
       
       
        
    }
};


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved