[LeetCode]/[Easy]

[Top Interview 150] 9. Palindrome Number

위대한먼지 2023. 7. 21. 22:00

Solution)

class Solution:
    def isPalindrome(self, x: int) -> bool:
        # Base Case
        if x < 0: return False
        
        # Initialization
        rev_x = 0
        original = x

        # Making a reversed x
        while x:
            rev_x = (rev_x * 10) + (x % 10)

            x //= 10
        
        # Check if palindrome
        if rev_x == original: return True
        return False

 
Problem: LeetCode
 
Time Complexity: O(n)
Space Complexity: O(1)

Explanation)

We'll make a reversed x integer and compare that with the original x to see if they are the same.
If they are the same, x is a palindrome.
 
 

Initialization)

The problem states that negative integers cannot be a palindrome. Thus, we'll put that as a base case.
 
Then there'll be a variable that will store the reversed x.
Because we'll be changing x while making a reversed x, we need to save the original value of x in a separate variable.
 

def isPalindrome(self, x: int) -> bool:
        if x < 0: return False
        
        rev_x = 0
        original = x

 
 

Reversing x)

We'll reverse x by adding digit by digit to rev_x. 
 
Make sure to multiply rev_x by 10 everytime you add a digit because rev_x is an integer not a string. By multiplying 10, you're making a space to add x's digit.
 
After you add a digit, you'll get rid of that digit in x by dividing it by 10. 
 
Repeat this process until x becomes 0. 
 

def isPalindrome(self, x: int) -> bool:
        ... # Initialization

        while x:
            rev_x = (rev_x * 10) + (x % 10)

            x //= 10

 
 

Return)

After the reversal is completed, we'll check if rev_x equals to original. We cannot compare rev_x with x because we've been changing x while reversing x. At this point, x = 0.
 
If they are the same, we return True.
 

def isPalindrome(self, x: int) -> bool:
        ... # Initialization

        while x:
            # Reversing x
        
        if rev_x == original: return True
        return False

 
 
 
TMI)
I first made a list that stored the digits of x and checked if that list was a palindrome using two pointers. But I thought I was wasting my memory, so I made a variable that will store a reversed x and compared that with the original x.
 
ALSOOO, I'm finally done with "easy" problems in Top Interview 150! Watch me suffer with harder problems hehe :)