LeetCode 7.整数翻转

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

示例 1:
输入: 123
输出: 321

示例 2:
输入: -123
输出: -321

示例 3:
输入: 120
输出: 21

注意:

假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。

JAVA实现

class Solution {
    public int reverse(int x) {
    if (x > Integer.MAX_VALUE || Math.abs(x) > Integer.MAX_VALUE) {
            return 0;
        }
        long res = 0;
        int tmp = Math.abs(x);
        while (tmp > 0) {
            res *= 10;
            res += tmp % 10;
            if (res > Integer.MAX_VALUE){
                return 0;
            }
            tmp /= 10;
        }
        return (int)(x > 0 ? res : -res );
    }
}

你可能感兴趣的:(LeetCode 7.整数翻转)