[LeetCode-07]整数反转(简单难度)

题目

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

例子1bash

输入: 123
输出: 321

例子2spa

输入: -123
输出: -321

例子3code

输入: 120
输出: 21

注意io

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

解题

class Solution {
    public int reverse(int x) {
        int result = 0;
        while(x != 0) {
            // 经过与10去余,获取x的最后一位数,放到n中
            int n = x % 10;
            // 判断反转后的结果是否越界
            if (result > Integer.MAX_VALUE/10 || (result == Integer.MAX_VALUE / 10 && n > 7)) return 0;
            if (result < Integer.MIN_VALUE/10 || (result == Integer.MIN_VALUE / 10 && n < -8)) return 0;
            // result * 10,将result向前进一位,并将n放到result的个位
            // 当result = 0时,进位无效
            result = (result * 10) + n;
            // x = x / 10,小数点向左,x被降一位
            x /= 10;
        }
        return result;
    }
}

经过%10获取整数x的个位数;时间

经过*10进一位;while

经过/10降一位;co

时间复杂度是O(log(x))数字

空间复杂度是O(1)

相关文章
相关标签/搜索