leetcode题解 7.Reverse Integer

题目:

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;

啦啦啦!

代码如下:

 class Solution {
public:
int reverse(int x) {
long long ans=;
bool isLittle=false;
if(x<)
{
x=-x;
isLittle=true;
}
while(x>)
{
int num=x%;
ans=ans*+num;
x=x/;
}
if(ans>INT_MAX||ans<INT_MIN)
return ;
if(isLittle)
return -ans;
else return ans;
}
};
上一篇:002_JS基础_JavaScript基础语法01


下一篇:关于Linux安装Mono 3.4的bug