LeetCode 7: Reverse Integer

Description:

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位有符号整数,反转该整数的数字。

例子1:

输入:123
输出:321

例子2:

输入:-123
输出:-321

例子3:

输入: 120
输出:21

注意:假设32比特数据可以保存的数字的范围为[-232, 232-1],当数字溢出时,返回0。

方法:

该方法的技巧之处在于如何检测数字溢出。

采用数学的方法实现数字的反转。

简述如下:

pop = x % 10
x = x / 10

temp = temp * 10 + pop

假设数字x为正值,判断转换后的数字是否溢出的条件如下:

1. 如果temp = temp * 10 + pop造成溢出,那么运算前temp的值temp >= INT_MAX/10
2. 如果temp > INT_MAX/10,那么temp = temp * 10 + pop一定溢出
3. 如果temp == INT_MAX/10,并且pop > 7,那么temp = temp * 10 + pop溢出。

这里,对于条件3,pop > 7的是因为32位整形表示的最大数字为2147483647。

相应地,对于负数,也做类似处理。

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

时间复杂度为O(lg(x)),空间复杂度为O(1)。

猜你喜欢

转载自www.cnblogs.com/alpaca/p/9488327.html