leetcode题解 7.Reverse Integer

Posted on 2018-04-06 17:57  wangziyan  阅读(135)  评论(0编辑  收藏  举报

题目:

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output:  321

 

Example 2:

Input: -123
Output: -321

 

Example 3:

Input: 120
Output: 21

 

Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

这个题目是一个easy的题目,但是细节要注意,第一点要注意记得处理负数的情况,

第二点就是记得看Note,Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

就是超过int的范围了就需要返回0。这一点非常重要,因为你要判断的是可能反转后会溢出,那么需要注意的就是

需要用一个long long来存储答案ans。判断使用的语句就是:

if(ans>INT_MAX||ans<INT_MIN)
            return 0;

啦啦啦!

代码如下:

 1 class Solution {
 2 public:
 3     int reverse(int x) {
 4         long long ans=0;
 5         bool isLittle=false;
 6         if(x<0)
 7         {
 8             x=-x;
 9             isLittle=true;
10         }
11         while(x>0)
12         {
13             int num=x%10;
14             ans=ans*10+num;
15             x=x/10;
16         }
17         if(ans>INT_MAX||ans<INT_MIN)
18             return 0;
19         if(isLittle)
20             return -ans;
21         else return ans;
22     }
23 };