[Swift] Reverse Integer

January 01, 2017 0 Comments

Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321


//Way1 mod取餘數去解
func reverse2(_ x: Int) -> Int {
    var y = x
    var returnVal = 0
    while (y != 0){
        returnVal = 10*returnVal + y%10
        y = y / 10
    }
    
    if (returnVal>Int.max || returnVal<Int.min) {
        return 0
    }else{
        return returnVal
    }
    
}

//Way2 string去解
func reverse(_ x: Int) -> Int {
    if x > Int.max || x < Int.min || x == 0 { return 0 }
    var returnVal = x
    var isNagative:Bool = false
    if x < 0 {
        isNagative = true
        returnVal = abs(x)
    }
    let myString = String(String(returnVal).characters.reversed())
    if Int(myString) != nil {
        if isNagative == true {
            return 0-Int(myString)!
        }else{
            return Int(myString)!
        }
    }else{
        return 0
    }
    
}

0 comments: