Description
https://leetcode.com/problems/reverse-integer/
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Explanation
The question is about writing a function to reverse an integer and return the reversed integer.
We make a while loop to perform reverse operation. For each loop, we divide the original number by 10 and add remainder to the result.
In Java, an integer is 32-bit ranging from 2³¹ – 1 to -2³¹. If the input number is -2³¹, it gets overflows after reversingbecause we wouldn’t have positive 2³¹. In that case, reversed * 10 / 10 != reversed, we return 0.
Java Solution
public class Solution {
public int reverse(int x) {
int reversed = 0;
while (x != 0) {
int temp = reversed * 10 + x % 10;
x = x / 10;
if (temp / 10 != reversed) {
return 0;
}
reversed = temp;
}
return reversed;
}
}
Python Solution
class Solution:
def reverse(self, x: int) -> int:
result = 0
is_negative = False
if x < 0:
is_negative = True
x = -x
while x > 0:
result = result * 10 + x % 10
x = x // 10
if result > 2**31 - 1 or result < -2**31:
return 0
if is_negative:
result = -result
return result
- Time Complexity: ~N
- Space Complexity: ~1