Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
Python
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
result = 0
if x < 0:
result = int('-' + str(x)[1:][::-1])
else:
result = int(str(x)[::-1])
if result >= 2**31 - 1 or result <= - 2**31:
return 0
else:
return result
Java
class Solution {
public int reverse(int x) {
String x_str = String.valueOf(x);
char[] result_chars = x_str.toCharArray();
char[] x_chars = x_str.toCharArray();
if (x_chars[0] == '-'){
for(int i = 1; i < x_str.length(); i ++){
result_chars[i] = x_chars[x_str.length() - i];
}
}else{
for(int i = 0; i < x_str.length(); i ++){
result_chars[i] = x_chars[x_str.length() - i - 1];
}
}
int result_int = 0;
try {
result_int = Integer.parseInt(String.valueOf(result_chars));
} catch (NumberFormatException e) {
e.printStackTrace();
}
return result_int;
}
}
参考答案
Python
class Solution:
# @param {int} n the integer to be reversed
# @return {int} the reversed integer
def reverseInteger(self, n):
if n == 0:
return 0
neg = 1
if n < 0:
neg, n = -1, -n
reverse = 0
while n > 0:
reverse = reverse * 10 + n % 10
n = n / 10
reverse = reverse * neg
if reverse < -(1 << 31) or reverse > (1 << 31) - 1:
return 0
return reverse
Java
public class Solution {
/**
* @param n the integer to be reversed
* @return the reversed integer
*/
public int reverseInteger(int n) {
int reversed_n = 0;
while (n != 0) {
int temp = reversed_n * 10 + n % 10;
n = n / 10;
if (temp / 10 != reversed_n) {
reversed_n = 0;
break;
}
reversed_n = temp;
}
return reversed_n;
}
}