LeetCode Reverse Integer,leetcodereverse

來源:互聯網
上載者:User

LeetCode Reverse Integer,leetcodereverse

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<strlen(s))        {            r[i]=s[j];            j--;            i++;        }        sscanf(r,"%d",&result);        if(strlen(s)>=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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.