Leetcode: 7. Reverse Integer
- Primary idea: Using
% 10
to reversely iterate through digits of the number, and use* 10
to update the result accordingly - Time Complexity: O(n)
- Space Complexity: O(1)
func reverse(_ x: Int) -> Int {
// make x to be mutable
var x = x
// inital value for the result
var reverseX = 0
// Iterate until x = 0
while x != 0 {
reverseX = reverseX * 10 + x % 10
x = x / 10
if reverseX > Int(Int32.max) || reverseX < Int(Int32.min) {
return 0
}
}
return reverseX
}
print(reverse(123)) // 321
print(reverse(-123)) // -321
print(reverse(120)) // 21
print(reverse(1300)) // 31
print(reverse(1534236469)) // 0
print(reverse(-9223372036854774999)) // 0
print(reverse(9223372036854774999)) // 0
print(reverse(-2147483412)) // -2143847412