您的位置:首页 > 其它

LeetCode-007 Reverse Integer

2017-12-06 15:26 501 查看

Description

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

Example

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.

Analyse

一道水题,将一个有符号整数反转,但需要注意的是,反转之后可能越界,这里投机取巧的方式就是让答案设为64位,若越界则返回0,否则强制类型转换回整型即可。

Code

class Solution {
public:
int reverse(int x) {
long ans=0;
while (x!=0) {
ans=ans*10+x%10;
x=x/10;
if (ans>INT_MAX || ans<INT_MIN) return 0;
}
return (int) ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: