从入门到“崩溃”,算法是硬伤.

反转整形

源代码

1
2
3
4
Example1: x = 123, return 321
Example2: x = -123, return -321

1.字符串法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution{
/// 字符串法
func reverse(x: Int) -> Int {
var negative: Bool = false
var m : Int = 0
if x < 0 {
m = x * -1
negative = true
}
var xStr = String(m)
let c: [Character] = xStr.characters.reversed()
let rStr = String(c)
if negative {
return -Int(rStr)!
}
return Int(rStr)!;
}
}

2.模十法

1
2
3
4
5
6
7
8
9
10
11
12
class Solution{
/// 模十法
func reverseMo10(x: Int) -> Int {
var result = 0
var tmp = abs(x)
while tmp > 0 {
result = result*10 + tmp%10
tmp/=10
}
return x > 0 ? result : -result
}
}