RSS Amplifier

Swift by An Tran · Apr 26, 2024

iOS Interview - Leetcode 7: Reverse Integer

0
Sign in to vote or save

This page did not load. You can still read it on the original site — the toolbar below keeps your place in the directory.

Leetcode: 7. Reverse Integer Primary idea: Using to reversely iterate through digits of the number, and use to update the result…

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

Read on antran.app

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.