# [LeetCode] 7. Reverse Integer 整数反转

Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1], then return 0.

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

Example 1:

Input: x = 123
Output: 321


Example 2:

Input: x = -123
Output: -321


Example 3:

Input: x = 120
Output: 21


Constraints:

• -2^31 <= x <= 2^31 - 1

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

class Solution {
public:
int reverse(int x) {
long res = 0;
while (x != 0) {
res = 10 * res + x % 10;
x /= 10;
}
return (res > INT_MAX || res < INT_MIN) ? 0 : res;
}
};

Github 同步地址：

https://github.com/grandyang/leetcode/issues/7

String to Integer (atoi)

Reverse Bits

https://leetcode.com/problems/reverse-integer/

https://leetcode.com/problems/reverse-integer/discuss/4060/My-accepted-15-lines-of-code-for-Java

https://leetcode.com/problems/reverse-integer/discuss/4056/Very-Short-(7-lines)-and-Elegant-Solution

LeetCode All in One 题目讲解汇总(持续更新中...)

posted @ 2014-11-27 09:04  Grandyang  阅读(34038)  评论(13编辑  收藏  举报