Palindrome Number
LeetCode #9 · Easy · Math · C++ solution with worked-out approach and complexity analysis.
Approach
String Conversion and Two Pointers
Convert the number to string, then compare characters from both ends.
Time
O(n)
n is the number of digits
Space
O(n)
the string representation
Problem description(from LeetCode)
Given an integer x, return true if x is a palindrome, and false otherwise.
Examples
Example 1
- Input:
- x = 121
- Output:
- true
- Note:
- 121 reads as 121 from left to right and from right to left.
Example 2
- Input:
- x = -121
- Output:
- false
- Note:
- From left to right, it reads -121. From right to left, it becomes 121-.
Example 3
- Input:
- x = 10
- Output:
- false
- Note:
- Reads 01 from right to left. Therefore it is not a palindrome.
Constraints
- •-2^31 <= x <= 2^31 - 1
C++ Solution
solution.cpp
class Solution {
public:
bool isPalindrome(int x) {
string s = to_string(x);
for (int i = 0, n = s.size(); i < n / 2; i++) {
if (s[i] != s[n - i - 1]) return false;
}
return true;
}
};