7. 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 hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Solution
(1) Java
Only pay attention to overflow when reverse
public int reverse(int x) {
if (x == 0) {
return x;
}
int sign = x > 0 ? 1 : -1;
int rst = 0;
x = Math.abs(x);
while (x > 0) {
if (rst*10/10 != rst) {
return 0;
}
rst = rst*10+x%10;
x = x/10;
}
return rst*sign;
}
(2) Python
Use extend slice method for string
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
sign = cmp(x, 0)
rst = int(str(sign*x)[::-1])
return rst*sign if rst < 2**31-1 else 0
(3) Scala
Recursion of course, still pay attention to overflow
object Solution {
def reverse(x: Int): Int = {
val sign = if (x >= 0) 1 else -1
val rst = helper(sign*x, 0)
return if (rst > Int.MaxValue) 0 else sign*rst
}
def helper(x: Int, rst: Int): Int = {
if (x == 0) {
return rst
}
if (rst*10/10 != rst) {
return 0
}
return helper(x/10, rst*10+x%10)
}
}