码迷,mamicode.com
首页 > 其他好文 > 详细

Reverse Integer

时间:2014-08-19 23:54:05      阅读:245      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   使用   os   io   

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 };

 

 

 

Reverse Integer,布布扣,bubuko.com

Reverse Integer

标签:des   style   blog   http   color   使用   os   io   

原文地址:http://www.cnblogs.com/bugfly/p/3923535.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!