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
- Start
- If x < 0 or (x > 0 and x % 10 == 0), return False
- Declare variable named backward
- Intialize backward to 0
- Repeat the steps until backward < x
- Increment backward by x % 10
- Update x // 10 to x
- Update backward * 10 to backward
- Check if backward is same with x or backward // 10 is same with x
- 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)\)
'Algorithm > Problems' 카테고리의 다른 글
[LeetCode] 20. Valid Parentheses (0) | 2022.10.14 |
---|---|
[LeetCode] 14. Longest Common Prefix (0) | 2022.10.14 |
[LeetCode] 13. Roman to Integer (0) | 2022.10.13 |
[LeetCode] 1. Two Sum (0) | 2022.10.13 |