首页 > 其他 > 详细

LeetCode: 7. 整数反转

时间:2019-08-16 11:03:22      阅读:76      评论:0      收藏:0      [点我收藏+]

给出一个 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)

LeetCode: 7. 整数反转

原文:https://www.cnblogs.com/aoeiuvAQU/p/11362007.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!