Reverse Integer Swift


  • 0
    C

    We will first check for most obvious negative and positive conditions for example if x < Int32.min or x > Int32.max is not met we will return false. And if the number is single digit we can return straight forward.
    Now we can reverse number

    func reverse(_ x: Int) -> Int {
        guard x >= Int(Int32.min), x <= Int(Int32.max) else {
            return 0
        }    
        if x > -10 && x < 10 {
            return x
        }
        var number = abs(x)
        var reverseNumber = 0
        while number > 0 {
            let reminder = number % 10
            reverseNumber = reverseNumber * 10 + reminder
            if reverseNumber > Int(Int32.max) {
                return 0
            }
            number = number / 10
        }    
        return x < 0 ? -reverseNumber : reverseNumber
    }
    

Log in to reply
 

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