美文网首页
Reverse Integer

Reverse Integer

作者: 敲一手烂代码 | 来源:发表于2018-01-31 22:25 被阅读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)!
    }
}

相关文章

网友评论

      本文标题:Reverse Integer

      本文链接:https://www.haomeiwen.com/subject/wvqrzxtx.html