[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
Example – 7913 ==== 3197
r | 0 | 30 | 310 | 3190 |
r | 3 | 31 | 319 | 3197 |
x | 791 | 79 | 7 | 0 |