Reverse Integer
程序员文章站
2024-03-22 14:17:52
...
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 hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
class Solution {
func reverse(_ x: Int) -> Int {
let sign = x >= 0 ? 1 : -1
var str = String(sign * x)
str = String(str.reversed())
if( sign * Int(str)! > Int32.max || sign * Int(str)! < Int32.min) {
return 0
}
return sign * Int(str)!
}
}
上一篇: 算法之寻找数组中的多数元素
下一篇: 23.链式存储结构--循环链表