您的位置:首页 > 其它

9. Palindrome Number

2016-01-19 23:26 232 查看
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.

Subscribe to see which companies asked this question

判断一个数字是否是回文,并且不需要额外的空间开销。

我的解法思路是

1窜数字如果顺着组合和倒着组合都相等,那么就认为这是回文。

即我们只要倒着组合一窜数字即可。

public boolean isPalindrome(int x) {

int tmp =x;
if(x<0)
{
return false;
}
else
{
int sum=0;
//依次取出低位到高位的各个数字。
while( x != 0)
{

sum *=10;
sum += x%10;
x = x/10;
}

//组合的数字和原来的相等,即认为是回文
if(sum == tmp)
return true;
else
return false;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: