您的位置:首页 > 编程语言 > C语言/C++

Leetcode 9. Palindrome Number

2016-04-23 10:38 344 查看
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.
大致题意:判断一个整形是否是回文整形,不能使用额外空间。
方法1:先逆置这个整数,比较他们是否相等(多用的了一个int额外空间但也能通过)
代码如下:

class Solution {
public:
bool isPalindrome(int x) {
if(x<0)
return false;
int i=x,rev=0;
while(i){
if(rev>INT_MAX/10||rev<INT_MIN/10)
return false;
rev=10*rev+i%10;
i/=10;
}
if(rev==x)
return true;
else
return false;
}
};
方法2:比较前后两个位是否相等,判断后去掉头尾两个位。

代码如下:


class Solution {
public:
bool isPalindrome(int x) {
if(x<0)
return false;
int div=1;
while(x/div>=10)
div*=10;
while(x!=0){//注意终止条件
int left=x/div;
int right=x%10;
if(left!=right)
return false;
x=(x%div)/10;
div/=100;
}
return true;
}
};
方法2参考来源:http://blog.csdn.net/feliciafay/article/details/17134663
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息