【Swift】LeedCode 拿硬币
由于各大平台的算法题的解法很少有Swift的版本,小编这边将会出个专辑为手撕LeetCode算法题。新手撕算法。请包涵!!!
给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。
如果反转后整数超过 32 位的有符号整数的范围 [−231, 231 − 1] ,就返回 0。
假设环境不允许存储 64 位整数(有符号或无符号)。
示例 1:
输入:x = 123
输出:321
示例 2:
输入:x = -123
输出:-321
示例 3:
输入:x = 120
输出:21
示例 4:
输入:x = 0
输出:0
Swfit解法如下:
class Solution {
func reverse(_ x: Int) -> Int {
var start = 0
//判断是否有负号
if abs(x) != x{
start = 1
}
var array:[String] = []
for item in String(x){
array.append(String(item))
}
var string = ""
for index in start..<array.count{
string = array[index] + string
}
if start == 1{
string = "-" + string
}
//依据题目判断是否反转后越界
if Double( Int(string)!) < pow(-2,31) || Double( Int(string)!) > pow(2,31)-1{
return 0
}
return Int(string)!
}
}