原文地址https://www.aclihui.com/leetcode-9-palindrome-number/
9. Palindrome Number
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
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: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:
Coud you solve it without converting the integer to a string?
分析
这是一道比较简单的题目
只要分析出来三个判断就可以
- 等于零
- 小于零
大于零
等于零
等于零肯定成立,因为零无论正着念,倒着读都是零
小于零
有题目知等于零的时候不成立
大于零
这是相对来说比较复杂的地方了,设置参数将x倒置比较即可
bool isPalindrome(int x) {
if(x==0)
{
return true;
}
else if(x<0)
{
return false;
}
else
{
int x1=x;
int y=0;
int tmp=0;
while(x1!=0)
{
tmp=x1%10;
x1=x1/10;
y=y*10+tmp;
}
if(x==y)
{
return true;
}
else
{
return false;
}
}
}