Given an integer x, return true if x is a palindrome, and false otherwise.
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
From: LeetCode
Link: 9. Palindrome Number
bool isPalindrome(int x) {
// Negative numbers are not palindromes
if (x < 0) {
return false;
}
int original = x;
long reversed = 0; // Use long to avoid integer overflow
// Reversing the number
while (x != 0) {
reversed = reversed * 10 + x % 10;
x /= 10;
}
// Check if the original number is equal to its reverse
return original == reversed;
}