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

LeetCode Reverse Integer

編輯:關於C++

Reverse Integer Total Accepted: 61132 Total Submissions: 219035 My Submissions Question Solution
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.

題意:反轉數字,但是要注意溢出的情況下,還有100的反序,對於溢出的情況下,返回0,100的反序為1而不是001。
先給出第一種解法:
既然是反轉,那麼最簡單的就是把數字看成字符串,然後進行逆序,負號進行特殊處理。然後使用sscanf把字符串化成數字。

對溢出的問題,可以這麼想,假設輸入是x,如果逆序溢出了的話,x的長度至少是10位,此外,假設逆序後的字符串為s1,sscanf後的數字為y,那麼這個y對應的字符串s2將和s1不相等!

代碼如下:

class Solution {
public:
    int reverse(int x) {
        int result=0;
        char s[12];
        char r[12];
        sprintf(s,"%d",x);
        int i=0;
        if(s[0]=='-'){
            r[0]='-';
            i++;
        }
        r[strlen(s)]='\0';
        int j=strlen(s)-1;
        while(i=10)//溢出的可能
        {
            sprintf(s,"%d",result);
            if(strcmp(r,s))
                result=0;
        }
        return result;
    }
};

1032 / 1032 test cases passed.
Status: Accepted
Runtime: 16 ms

第二種解法:
額, 其實這才是最簡單的方法,通過反復將個位上的數字前移就好了,如果溢出直接返回0!

class Solution {  
public:  
    int reverse(int x) {    
        const int max = 0x7fffffff;  //int最大值  
        const int min = 0x80000000;  //int最小值  
        long long sum = 0;   

        while(x != 0)  
        {  
            int temp = x % 10;  
            sum = sum * 10 + temp;  
            if (sum > max || sum < min)   //溢出處理  
                return 0;  
            x = x / 10;  
        }  
        return sum;  
    }  
}; 

1032 / 1032 test cases passed.
Status: Accepted
Runtime: 14 ms

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