六月箴言html
git
第二周算法记录算法
007 -- Reverse Integer (整数反转)swift
题干英文版:this
Given a 32-bit signed integer, reverse digits of an integer.spa
Example 1:code
Input: 123
Output: 321htm
Example 2:blog
Input: -123
Output: -321ci
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。
一、大于最大
从result * 10 + tempInt > MAX_VALUE这个溢出条件来看
当出现 result > MAX_VALUE / 10 且 还有tempInt须要添加时,则必定溢出
当出现 result == MAX_VALUE / 10 且 tempInt > 7 时,则必定溢出,7是2^31 - 1的个位数
二、小于最小
从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
有缘看到的亲们:文中如有不对之处,还请劳驾之处,谢谢!