leetcode题解 9. Palindrome Number

时间:2023-03-09 16:43:50
leetcode题解 9. Palindrome Number

9. Palindrome Number

题目:

Determine whether an integer is a palindrome. Do this without extra space.

click to show spoilers.

Some hints:

Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

其实就是判断一个数字是不是回文数字。

一开始的思路是找到开始的数字和最后的数字进行比对,发现自己有点天真,哈哈哈,又不是字符串啦,不好比较。

正确的思路就是求出它的相反的那个数,然后判断他们两是不是相等的。

负数的情况感觉应该特判一下都不是回文,没有特判也过了,下面是代码:

 class Solution {
public:
bool isPalindrome(int x) {
int reverse=;
int temp=x;
while(temp>)
{
reverse=reverse*+temp%;
temp=temp/;
}
if(x==reverse)
return true;
else
return false;
}
};