您的位置:首页 > 其它

LeetCode——Reverse Integer

2018-02-25 16:04 411 查看

LeetCode——Reverse Integer

# 7

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.

整数的反转,思路是很简单的,难点是考虑反转之后的溢出。可以使用long long型数据。

C++

class Solution {
public:
int reverse(int x) {
long long res = 0;
bool isPositive = true;
if(x < 0) {
isPositive = false;
x = x * -1;
}
while(x > 0) {
res = res * 10 + x % 10;
x = x / 10;
}
if(res > INT_MAX)
return 0;
if(isPositive)
return res;
else
return -res;
}
};


另一种简洁的做法,是不考虑符号位。

-C++

class Solution {
public:
int reverse(int x) {
int res = 0;
while (x != 0) {
if (abs(res) > INT_MAX / 10) return 0;
res = res * 10 + x % 10;
x /= 10;
}
return res;
}
};


也可以将两种结合在一起。

-C++

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