7. Reverse Integer (Easy)
https://leetcode.com/problems/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 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.
Solutions
class Solution {
long MIN = 1 << 31;
long MAX = (1 << 31) - 1;
public int reverse(int x) {
long ans = 0;
long tmp = x;
while (tmp != 0) {
long remainder = tmp % 10;
tmp = tmp / 10;
// return immediately if overflow takes place.
if (x > 0 && ans * 10 + remainder > MAX) {
return 0;
}
// return immediately if overflow takes place.
if (x < 0 && ans * 10 + remainder < MIN) {
return 0;
}
ans = ans * 10 + remainder;
}
return (int) ans;
}
}