[Leetcode] 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.

题意:判断一个整数是否为回文数。

思路:常规思路是,将数字转换成字符串或者用数组保存各位上的值,然后从两端开始遍历,判断是否为回文,或者将数反转以后,判断是否相等(这时要注意,若是数很大,怎么办,会溢出)。以上都不行,我就想,数为回文,要高位和低位上的值对应相等,那如何取得各个位上的值了?要是知道这个整数有多少位,就可以取余,或者求商得到对应位的值。按这个思路,我们首先求出的是这个数的位数,我们可以通过不断除10来得到位数。这里值得注意的是:每次比较完以后,如何找到下一对位置上值的比较。代码如下:

 class Solution {
public:
bool isPalindrome(int x)
{
if(x<) return false;
if(x<) return true; int base=;
while(x/base>=)
base*=; while(x)
{
int lNum=x/base;
int rNum=x%;
if(lNum !=rNum)
return false; x-=lNum*base;
x/=;
base/=;
}
return true;
}
};
上一篇:C#语言基础——结构体和枚举类型


下一篇:记录java/javascript让浮点数显示两位小数的方法