Description#
Determine whether an integer is a palindrome. A palindrome is a number that reads the same forward as backward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: From right to left, it becomes 01. Therefore it is not a palindrome.
Follow up:
Could you solve it without converting the integer to a string?
Approach#
- The advanced hint from the problem actually suggests a method of converting to a string
- However, it can be seen from the problem that there are many similarities with the previous integer reverse problem, just add a comparison step after reversing, so the code for the previous problem can be slightly modified
bool isPalindrome(int x){
if(x < 0)//Negative numbers are not palindromes
return false;
int x_value = x;
long next_x = 0;
while(x_value) {
next_x = next_x * 10 + x_value % 10;
x_value /= 10;
}
//May overflow after reversing, so need to use long type and convert to int type for comparison
if(x == (int)next_x)
return true;
else
return false;
}
Note#
- Consider overflow when comparing after reversing