Algorithm/Problems

[LeetCode] 9. Palindrome Number

See_the_forest 2022. 10. 13. 10:42

1. Description

Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward.

 

For example, 121 is a palindrome while 123 is not.

 

constraints :

  • \(-2^{31} <= x <= 2^{31} - 1\)

 

2. Algorithms

To check given integer is a palindrome number, we need to compar two integer one for original and the other for backward of original.

 

To get backward integer, we need iterative calculation updating input integer x. We will repeat the steps until backward integer is bigger than x.

 

x = 121 

iteration1 : 
    - x % 10 -> 1 
    - x // 10 -> 12 
    - backward += x % 10 -> 1 
    - backward = backward * 10 -> 10 
    
iteration2 : 
    - x % 10 -> 2 
    - x // 10 -> 1 
    - backward += x % 10 -> 12

 

  1. Start
  2. If x < 0 or (x > 0 and x % 10 == 0), return False
  3. Declare variable named backward
  4. Intialize backward to 0
  5. Repeat the steps until backward < x
    1. Increment backward by x % 10
    2. Update x // 10 to x
    3. Update backward * 10 to backward
  6. Check if backward is same with x or backward // 10 is same with x
  7. End

 

3. Codes

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if (x < 0) or (x > 0 and x % 10 == 0): return False 

        backward = 0 
        while backward < x: 
            backward = (backward * 10) + x % 10 
            x = x // 10 

        return (backward == x) or (backward // 10 == x)

 

4. Conclusion

 

Time Complexity : \(O(N^2)\)

Space Complexity : \(O(1)\)