Palindrome
Number Total Accepted: 74363 Total Submissions: 261192Determine 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.
这道题跟之前的球最长回文的关系其实不大,相反和前一题求一个数的反转更接近。这道题的思路很简单,和上一题类似,就是求这个数的反转,如果这个反转与原来的数相同,那么这个数本身就是一个回文。在这道题的讨论中看到一个这个算法的改进,原帖地址:https://leetcode.com/discuss/33500/an-easy-lines-code-only-reversing-till-half-and-then-compare ,即不用完全反转整个数,反转一半即可。
int num = 0;
while(x > num)
{
num = num * 10 + x % 10;
x = x / 10;
}
if(x == num / 10 || x == num)
return true;
else
return false;
这个地方其实比较巧妙,如果双数位数的回文数,例如:123321,那么将会以x=num退出,然后再后面的if语句中返回true;如果单数位数的回文数,例如:12321,那么将会以x < <script id="MathJax-Element-593" type="math/tex"><</script>num退出,退出时x=12,num=123,但后面的if语句仍然可以返回true。而其他的偶数位数的数将会有两大类情况,例如123456,将会以x < <script id="MathJax-Element-594" type="math/tex"><</script>num退出,x=123,num=654,此时x = num / 10 和 x = num均不可能满足,首先它们本身不相等,其次它们的位数相同,所以不可能相差10倍。另一类:654321,将会以x < <script id="MathJax-Element-595" type="math/tex"><</script>num退出,x=65,num=1234,它们本身不相等,其次它们位数差2位,所以不可能差10倍。对于其他的奇数位数的情况,例如:12345(54321也是一样的情况),将会以x < <script id="MathJax-Element-596" type="math/tex"><</script>num退出,x=12,num=543,它们的位数差1位,所以不可能相等,如果x=num/10,那么个数必然是回文,因为中间位不影响,num/10就是取前两位,前两位=后两位,当然是回文,所以x ≠ num/10;
另外要提一下可以有一个排除条件:如果这个数字是10的倍数,那么除了0以外,都不会是回文,这点很明显,int中10就是10,不能写成010.
下面是完整程序代码:
#include <iostream>
using namespace std;
bool isPalindrome(int x)
{
if(x<0 || x!=0 && x % 10 == 0)
return false;
int num = 0;
while(x > num)
{
num = num * 10 + x % 10;
x = x / 10;
}
if(x == num / 10 || x == num)
return true;
else
return false;
}
int main()
{
int x;
cout<<"Input the number:"<<endl;
cin>>x;
cout<<isPalindrome(x)<<endl;
return 0;
}