LeetCode 【2】 Reverse Integer --007

六月箴言

万物之中,希望最美;最美之物,永不凋零。—— 斯蒂芬·金

 

第二周算法记录

007 -- Reverse Integer (整数反转)

题干英文版:

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 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

注意:

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

 

解题思路:如果不考虑数值范围,题目非常好实现,依赖于整数除法和求余即可实现

因为本体是要求必须是32位的有符号整数,需要判断溢出条件:

设当前计算结果为result,下一位为tempInt。
1、大于最大

从result * 10 + tempInt > MAX_VALUE这个溢出条件来看
当出现 result > MAX_VALUE / 10 且 还有tempInt需要添加时,则一定溢出
当出现 result == MAX_VALUE / 10 且 tempInt > 7 时,则一定溢出,7是2^31 - 1的个位数

2、小于最小

从result * 10 + tempInt < MIN_VALUE这个溢出条件来看
当出现 result < MIN_VALUE / 10 且 还有tempInt需要添加 时,则一定溢出
当出现 result == MAX_VALUE / 10 且 tempInt < -8 时,则一定溢出,8是-2^31的个位数

具体实现为:

 func reverse(_ x: Int) -> Int {
        var originInt = x
        guard originInt != 0 else {
            print("originInt = 0")
            return 0
        }
        var result = 0
        var tempInt = 0
        while (originInt != 0) {
            tempInt = originInt%10
            originInt = originInt/10
            if (result > Int32.max/10 || (result == Int32.max / 10 && tempInt > 7)) {
                print("最大溢出")
                return 0
            }
            if (result < Int32.min/10 || (result == Int32.min / 10 && tempInt < -8) ){
                print("最小溢出")
                return 0
            }
            result = result*10 + tempInt
        }
        return result  
    }

 

1032 / 1032 test cases passed.
Status: Accepted
Runtime: 4 ms
Memory Usage: 20.4 MB

 

备注:关于时间和空间复杂度还不太会分析

 

 

往期Leetcode

 Two Sum 

 

 有缘看到的亲们:文中若有不对之处,还请劳驾之处,谢谢!

posted on 2019-06-09 11:17  Dev_F  阅读(156)  评论(0编辑  收藏  举报

导航