【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: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

翻译

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

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

分析

这道题目不考虑溢出就简单很多。解决溢出可以通过循环将该数字进行取模和除法运算进行判断。溢出有两种情况一个是大于整数最大值
MAX_VALUE (2^31 − 1 = 2147483647),另一个是小于整数最小值 MIN_VALUE (−2^31= -2147483648)

result计算结果,y表示求余结果。则溢出条件则为:

result * 10 + y > MAX_VALUE 

result * 10 + y < MIN_VALUE

具体溢出情况如下

  • 当出现 result > MAX_VALUE / 10 且 还有y需要相加 时。

  • 当出现 result == MAX_VALUE / 10y > 7 时,7是MAX_VALUE的个位数。

  • 当出现 result < MIN_VALUE / 10 且 还有y需要相加 时。

  • 当出现 result == MIN_VALUE / 10 y < -8 时,8是MIN_VALUE的个位数。


Kotlin代码实现


fun reverse(num: Int): Int {
    var x = num
    var result = 0
    while (x != 0) {
        val y = x % 10
        if (result > Integer.MAX_VALUE / 10 || result == Integer.MAX_VALUE / 10 && y > 7)
            return 0
        if (result < Integer.MIN_VALUE / 10 || result == Integer.MIN_VALUE / 10 && y < -8)
            return 0
        result = result * 10 + y
        x /= 10
    }
    return result
}

参考:
https://leetcode.com/problems/reverse-integer

原文地址:https://www.cnblogs.com/MillerKevin/p/12799254.html