LeetCode: 7. 整数反转

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

示例 1:

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

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

输入: 120
输出: 21
注意:

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

思路:

这道题最主要的就是注意反转之后会溢出,所以在反转期间要注意每次操作是否造成溢出

//判断是否越界
if (result > Integer.MAX_VALUE / 10 || (result == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
if (result < Integer.MIN_VALUE / 10 || (result == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
public int reverse(int x) {
    int result = 0;
    while(x != 0) {
       int pop = x % 10;
       //判断是否越界
       if (result > Integer.MAX_VALUE / 10 || (result == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
       if (result < Integer.MIN_VALUE / 10 || (result == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
       result = result * 10 + pop;
       x /= 10;
    }
       return result;
}

复杂度分析

时间复杂度:O(log(x)),x 中大约有 log10(x)位数字

空间复杂度:O(1)。

作者:LeetCode
链接:https://leetcode-cn.com/problems/two-sum/solution/zheng-shu-fan-zhuan-by-leetcode/
来源:力扣(LeetCode)

猜你喜欢

转载自www.cnblogs.com/aoeiuvAQU/p/11362007.html