How to reverse an Integer ?

[Question]: Reverse Integer in swift ex. 12345 => 54321 output should lie in Int32 Range

TC: O(n)
SC: O(1)

func reverse(_ x: Int) -> Int {
    var r = 0, x = x
    while x != 0 {
        r = r * 10
        r = r + (x % 10)
        x /= 10
    }
    return r < Int32.min || r > Int32.max ? 0 : r
}
print(reverse(12345))

Explanation: Here we are multiplying result with10 further adding it to modulo(reminder) & get last element by divide by 10

r0303103190
r3313193197
x7917970
This is explanation of code

Leave a Comment

Your email address will not be published. Required fields are marked *