LeetCode_Simple_7. Reverse Integer

2019.1.8

题目描述:

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

这道题要将提供的32位的有符号整数翻转过来,要注意的是溢出问题,因为int型的数值范围是 -2147483648~2147483647, 那么如果我们要翻转 1000000009 这个在范围内的数得到 9000000001,翻转后的数就超过了范围,会溢出

解法一:

用long long 型数据,怎么翻转都不会出现溢出(其实有点钻空子的意味。。)

C++代码:
 

/**
 * Correct but can refactor the code.
 */
class Solution {
public:
    int reverse(int x) {
        long long res = 0;
        bool isPositive = true;
        if (x < 0) {
            isPositive = false;
            x *= -1;
        }
        while (x > 0) {
            res = res * 10 + x % 10;
            x /= 10;
        }
        if (res > INT_MAX) return 0;
        if (isPositive) return res;
        else return -res;
    }
};

解法二:官方解答

方法:弹出和推入数字 & 溢出前进行检查

思路

我们可以一次构建反转整数的一位数字。在这样做的时候,我们可以预先检查向原整数附加另一位数字是否会导致溢出。

算法

反转整数的方法可以与反转字符串进行类比。

我们想重复“弹出” x 的最后一位数字,并将它“推入”到 rev 的后面。最后,rev 将与 x 相反。

要在没有辅助堆栈 / 数组的帮助下 “弹出” 和 “推入” 数字,我们可以使用数学方法。

//pop operation:
pop = x % 10;
x /= 10;

//push operation:
temp = rev * 10 + pop;
rev = temp;

但是,这种方法很危险,因为当temp=rev*10+pop 时会导致溢出。

幸运的是,事先检查这个语句是否会导致溢出很容易。

为了便于解释,我们假设rev 是正数。

  1. 如果 temp = rev*10 +pop 导致溢出,那么一定有rev≥INTMAX​/10。
  2. 如果 rev>INTMAX/10​,那么 temp=rev⋅10+pop 一定会溢出。
  3. 如果 rev==INTMAX​/10,那么只要 pop>7,temp=rev⋅10+pop 就会溢出。

当rev 为负时可以应用类似的逻辑。

class Solution {
public:
    int reverse(int x) {
        int rev = 0;
        while (x != 0) {
            int pop = x % 10;
            x /= 10;
            if (rev > INT_MAX/10 || (rev == INT_MAX / 10 && pop > 7)) return 0;
            if (rev < INT_MIN/10 || (rev == INT_MIN / 10 && pop < -8)) return 0;
            rev = rev * 10 + pop;
        }
        return rev;
    }
};

复杂度分析

  • 时间复杂度:O(log(x)),x 中大约有log10​(x) 位数字。
  • 空间复杂度:O(1)。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值