Palindrome Number Swift


  • 0
    C

    Wikipedia definition of Palindrome "A palindrome is a word, phrase, number, or another sequence of characters which reads the same backward as forward, such as madam or racecar."

    Approach 1 Convert to string (Accepted):
    Convert number to a string and then traverse from start and end and do a comparison if there is mismatch it means the number is not a palindrome.

    Single digit without a sign is always palindrome so we will return true for that case at the start.

    func isPalindrome(_ x: Int) -> Bool {
    
        if x >= 0 && x < 10 {
            return true
        }
        let string = "\(x)"
        var startIndex = string.characters.startIndex
        var endIndex = string.characters.endIndex
        endIndex = string.characters.index(before: endIndex)
        while startIndex < endIndex {
            if string.characters[startIndex] != string.characters[endIndex] {
                return false
            }
            startIndex = string.characters.index(after: startIndex)
            endIndex = string.characters.index(before: endIndex)
        }
        return true
    }
    

    Complexity: O(n) where n is the length of the input number

    Approach 2 Reversing number (Accepted)
    Converting number to a string and then parsing them is not cost effective and add some complexity.
    So little bit better approach will be to reverse input number and compare input with a reversed number if they are equal it's a palindrome.

    func isPalindrome(_ x: Int) -> Bool {
        var number = x
        var reverseNumber = 0
        while number > 0 {
            let reminder = number % 10
            reverseNumber = reverseNumber * 10 + reminder
            number = number / 10
        }
        return x == reverseNumber    
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.