Determine whether an integer is a palindrome. Do this without extra space.
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 将整数转换成倒序的整数,然后比较两个数是否相等
2 提取头尾两个数,然后判断它们是否相等,判断后去掉头尾两个数
#include <iostream>
using namespace std;
class Solution {
public:
bool isPalindrome(int x) {
int y=x;
if(y<0){
return false;
}
int maxNum[10]={2,1,4,7,4,8,3,6,4,7};
bool flag=false;
// bool isNeg=false;
// if(y<0){
// y=-y;
// isNeg=true;
// }
if(y/1000000000!=0){
flag=true;
}
int s=0,j=0,m;
while(y!=0){
m=y%10;
if(flag){
if(m>maxNum[j]){
return false;
}else if(m<maxNum[j]){
flag=false;
}
j++;
}
y=y/10;
s=s*10+m;
}
// if(isNeg){
// s=-s;
// }
if(s==x){
return true;
}else{
return false;
}
// return s;
}
};
int main(){
Solution sol;
cout<<sol.isPalindrome(-2147447412)<<endl;
}
本文介绍了一种不使用额外空间判断整数是否为回文数的方法。通过将整数反转并与原数对比来实现,同时考虑了负数和整数溢出的问题。
2076

被折叠的 条评论
为什么被折叠?



