Reverse Integer

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?

Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).

 

这题关键要考虑溢出的问题,在O(1)的空间复杂度,如果返回int,溢出应该返回什么,这里如果正溢出,则返回INT_MAX,负溢出,则返回INT_MIN,代码如下:

 

 1 class Solution {
 2 public:
 3     int reverse(int x) {
 4         bool minus = x < 0;
 5         if( minus ) x = -x;
 6         long long ans = 0;  //使用long long就可以处理int型的溢出
 7         while( x ) {    //反转进行时......
 8             ans = ans * 10 + x % 10;
 9             x /= 10;
10         }
11         if( ans > INT_MAX ) return ( minus ? INT_MIN : INT_MAX );   //处理正溢出和负溢出的情况
12         return ( minus ? -ans : ans );  //处理正数和负数的情况
13     }
14 };

 

 

 

posted on 2014-08-19 23:29  bug睡的略爽  阅读(138)  评论(0编辑  收藏  举报

导航