Asked 3 months ago
0Comments
2 Views
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0) {
return false;
}
// Numbers ending in 0 that are not 0 are not palindromes
if (x != 0 && x % 10 == 0) {
return false;
}
int result = 0;
int temp = x;
while(temp > 0) {
int digit = temp % 10;
result = result * 10 + digit;
temp = temp / 10;
}
return result == x;
}
};
x
is negative, return false
immediately.x
ends with 0 (and is not 0 itself), return false
immediately.result
to 0 and temp
to x
.x
by extracting digits from temp
and appending to result
.result
with original x
, return true
if equal.x = 121
x = 121
, temp = 121
, result = 0
digit = 121 % 10 = 1
, result = 0 * 10 + 1 = 1
, temp = 121 / 10 = 12
digit = 12 % 10 = 2
, result = 1 * 10 + 2 = 12
, temp = 12 / 10 = 1
digit = 1 % 10 = 1
, result = 12 * 10 + 1 = 121
, temp = 1 / 10 = 0
result == x
, return true
Now, let's look at the second approach:
Approach 2: Converting to string and using two pointers
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0) {
return false;
}
string str = to_string(x);
int start = 0;
int end = str.size() - 1;
while (start < end) {
if (str[start] != str[end]) {
return false;
}
start++;
end--;
}
return true;
}
};
This approach works by converting the number to a string and checking if it reads the same from both ends. It's more intuitive but involves string conversion.
Comparison:
Both approaches are valid and have their merits. Approach 1 is more efficient in terms of space and potentially time for very large numbers, while Approach 2 is more straightforward and easier to understand at a glance. The choice between them might depend on specific requirements or preferences in a given situation.
Share