Here’s a simple method for getting the reverse of a positive integer.
1. Get the last digit
let lastDigit = num % 10
2. Append the last digit to the reverse
reversedNum = (reversedNum * 10) + lastDigit
3. Remove the last digit from the original number
num = num / 10
Putting it all together into a loop, we have:
func reverse(_ input: Int) -> Int {
var num = input // create a mutable copy
var reversedNum = 0 // result
while num > 0 {
let lastDigit = num % 10
reversedNum = (reversedNum * 10) + lastDigit
num = num / 10
}
return reversedNum
}
reverse(123) // returns 321