LeetCode - 7.Reverse Integer

整数反转

Given a 32-bit signed integer, reverse digits of an integer.
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.

给一个32位的有符号整数,翻转这个数字。
注意:
假设我们在一个只能处理32位有符号整数范围的环境中。为了解决这个问题,假如翻转后的数字溢出则函数返回0。

Example:

Input: 123
Output:  321

Input: -123
Output: -321

Input: 120
Output: 21

分析: 32位的整数范围为: -2147483648 ~ 2147483648,因此,正常返回结果的数字需要在-231 ~ 231范围内。翻转可以使用字符串来实现。

# Python
def reverse(x):
    str_x = str(abs(x))
    num = int(str_x[::-1])
    if num > 2147483648: return 0
    if x < 0: return -num
    return num
// Java
public int reverse(int x) {
    String xs = String.valueOf(x < 0 ? -x : x);
    char[] ch = new char[xs.length()];
    for (int i = 0; i < xs.length(); i++) {
        ch[i] = xs.charAt(i);
    }
    for (int i = 0; i < (ch.length / 2); i++) {
        char t = ch[i];
        ch[i] = ch[ch.length - 1 - i];
        ch[ch.length - 1 - i] = t;
    }
    String res = String.valueOf(ch);
    try {
        return x < 0 ? -Integer.valueOf(res) : Integer.valueOf(res);
    } catch (NumberFormatException e) {
        return 0;
    }
}

你可能感兴趣的:(LeetCode - 7.Reverse Integer)