A solution in Swift


  • 0
    O
    class Solution {
        func reverse(_ x: Int) -> Int {
            var isNegative = false
            var original = x
            if original < 0 { original = (-1) * original; isNegative = true }
            var result = 0
            while original > 0 {
                result = (result * 10) + (original % 10)
                original /= 10
            }
            guard result < 0x7FFFFFFF else { return 0 }
            if isNegative { result = result * (-1) }
            return result
        }
    }
    

  • 0
    T

    @ozanasan, why do you compare to 0x7FFFFFFF ?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.