Reverse Integer
2018-01-31 本文已影响12人
敲一手烂代码
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)!
}
}