1. 程式人生 > >leetcode 7. Reverse Integer(C語言,翻轉一個整數,判斷是否溢位)19

leetcode 7. Reverse Integer(C語言,翻轉一個整數,判斷是否溢位)19

貼原題:

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.

Note: The input is assumed to be a 32-bit signed integer. Your
function should return 0 when the reversed integer overflows.

解析:
  本題是要讓翻轉一個32位的整數,負數只翻轉數值部分,符號位保持不變。
  我感覺這道題最難的點在於如何判斷一個數翻轉之後是否溢位。(這一點我一會在下面做個總結)

貼程式碼:

int reverse(int x) {
    int y=0;//需要返回的數
    while(x)
    {
        int temp=y;//暫存y的值
        y=y*10+x%10;//倒序;把x的最低位依次壓入y的最低位
        if((y-x%10)/10!=temp)//反向推,若推不出原值則溢位
        {
            return 0;
        }
        x/=10
; } return y; }

總結:
  如何判斷是否溢位?
  其實看我上面的程式碼也可以看得出了,只要把這個式子反著推過來,再來看是否相等就行了。

  1. 加法溢位判斷:若c=a+b; c-a!=b則溢位;或者a, b>0, c<0溢位;或者a, b<0, c>0溢位;
  2. 減法溢位判斷:若c=a-b; c+b!=a則溢位;
  3. 除法溢位判斷:若b!=0 && a/b=c; b*c!=a則溢位
  4. 乘法溢位判斷:若c=a*b; a!=0 && c/a!=b則溢位

      以上全為我個人總結,如有錯誤還請大家指出!