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 store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Related Topics:
Math
Similar Questions:
// OJ: https://leetcode.com/problems/reverse-integer/
// Author: github.com/lzl124631x
// Time: O(1)
// Space: O(1)
class Solution {
public:
int reverse(int x) {
if (x == INT_MIN) return 0;
int r = 0, sign = x >= 0 ? 1 : -1, y = sign * x, p = 1;
while (y) {
y /= 10;
if (y) p *= 10;
}
x = sign * x;
while (x) {
int d = x % 10;
x /= 10;
if ((INT_MAX - r) / p < d) return 0;
r += p * d;
p /= 10;
}
return sign * r;
}
};
// OJ: https://leetcode.com/problems/reverse-integer/
// Author: github.com/lzl124631x
// Time: O(1)
// Space: O(1)
class Solution {
public:
int reverse(int x) {
int r = 0;
while (x) {
int d = x % 10;
x /= 10;
if ((r >= 0 && (r > INT_MAX / 10 || INT_MAX - 10 * r < d))
|| (r < 0 && (r < INT_MIN / 10 || INT_MIN - 10 * r > d))) return 0;
r = r * 10 + d;
}
return r;
}
};