leetcode 7. Reverse 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. 
 
这道题实现并不难,就是溢出问题。
32位有符号数,最高位表示符号,剩下31位表示数值,那么最大可以表示0x7fffffff,最小可以表示0x80000000
我们要处理溢出的情况,在reverse的过程中,有可能会出现溢出的情况,此时要返回0
 
 1 class Solution {
 2 public:
 3     int reverse(int x) {
 4         
 5         const int max = 0x7fffffff;  //int最大值
 6         const int min = 0x80000000;  //int最小值
 7         long long sum = 0; 
 8         
 9         while(x != 0)
10         {
11             int temp = x % 10;
12             sum = sum * 10 + temp;
13             if (sum > max || sum < min)  return 0;   //处理溢出
14             x = x / 10;
15         }
16         return sum;
17     }
18 };

 

posted @ 2015-12-24 16:09  0giant  阅读(195)  评论(0编辑  收藏  举报