欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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)!
    }
}