ID | Title | Difficulty | |
---|---|---|---|
Loading... |
7. Reverse Integer
Medium
LeetCode
Math
Problem
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$
Code
class Solution {
public int reverse(int x) {
int res = 0;
while(x != 0) {
int digit = x % 10;
int temp = res * 10 + digit;
if(temp / 10 != res){
return 0;
}
res = temp;
x /= 10;
}
return res;
}
}
class Solution {
public int reverse(int x) {
int res = 0;
while(x != 0){
int digit = x % 10;
if(res > 0){
if(res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && digit > Integer.MAX_VALUE % 10)){
return 0;
}
} else if (res < 0){
if(res < Integer.MIN_VALUE / 10 || (res == Integer.MIN_VALUE / 10 && digit < Integer.MIN_VALUE % 10)){
return 0;
}
}
res = res * 10 + digit;
x /= 10;
}
return res;
}
}
class Solution:
def reverse(self, x: int) -> int:
sign = [1, -1][x < 0] # sign[True] = -1, sign[False] = 1
rev, x = 0, abs(x)
while x:
x, mod = divmod(x, 10)
rev = rev * 10 + mod
# -2**31 <= x <= 2**31 - 1
if sign == 1 and rev > 2 ** 31 - 1:
return 0
if sign == -1 and rev > 2 ** 31:
return 0
return sign * rev
按 <- 键看上一题!
6. Zigzag Conversion
按 -> 键看下一题!
8. String to Integer (atoi)