iOS Interview - Leetcode 9: Palindrome Number

April 23, 20242 min read#swift, #interview, #leetcode

Leetcode: 9. Palindrome Number

  • Primary idea: Calculate the reverted value and compare it with the original value.
  • Time Complexity: O(1)
  • Space Complexity: O(1)
func isPalindrome(_ x: Int) -> Bool {
    // Special cases:
    // When x < 0, x is not a palindrome.
    // Also if the last digit of the number is 0, in order to be a palindrome,
    // the first digit of the number also needs to be 0.
    // Only 0 satisfy this property.
    if (x < 0 || (x % 10 == 0 && x != 0)) {
        return false;
    }

    var revertedNumber = 0
    var y = x

    while y > 0 {
        revertedNumber = revertedNumber * 10 + y % 10
        y /= 10
    }

    // When the length is an odd number, we can get rid of the middle digit by revertedNumber/10
    // For example when the input is 12321, at the end of the while loop we get x = 12, revertedNumber = 123,
    // since the middle digit doesn't matter in palidrome(it will always equal to itself), we can simply get rid of it.
    return revertedNumber == x || x == revertedNumber/10
}

isPalindrome(121) // true
isPalindrome(-121) // false
isPalindrome(10) // false
Quick Drop logo

Profile picture

Personal blog by An Tran. I'm focusing on creating useful apps.
#Swift #Kotlin #Mobile #MachineLearning #Minimalist


© An Tran - 2024