2087人阅读 评论(0)

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.

Input: 1001

Output: false

Expected: true

Input: 1000110001

Output: false

Expected: true

Input: 1020110201;

Output: false

Expected: true

class Solution {
public:
bool isPalindrome(int x) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(x==INT_MIN)
return false;
if(x==0)
return true;
if(x<0)//测试得知，Online Judge应该是默认认为全部负数都return false。
return false;

while(x){
if((x<100)&&(x>10)&&(x%11==0))
return true;
if(x<10)
return true;
int count=0;
int large_digit=x;
int large_digit2=x;

while(large_digit2>=100){
large_digit2=large_digit2/10;
count++;
}
large_digit=large_digit2/10;
count++;
int small_digit=x-x/10*10;
int y=x/10;
int small_digit2=y-y/10*10;
//            std::cout<<"large_digit2="<<large_digit2<<",small_digit2="<<small_digit2<<std::endl;
if(large_digit2%10==0&&small_digit2==0)
x = (x - (int)pow(10,count)*large_digit)/10+1*pow(10,count-2)+1;
else if(large_digit2==10&&small_digit2!=0)
return false;
else
x = (x - (int)pow(10,count)*large_digit)/10;
//            std::cout<<"larget_digit="<<large_digit<<",small_digit="<<small_digit<<",new x="<<x<<std::endl;
if(small_digit!=large_digit)
return false;

}
return true;
}
};

bool isPalindrome(int x) {
if (x < 0) return false;
int div = 1;
while (x / div >= 10) {
div *= 10;
}
while (x != 0) {
int l = x / div;
int r = x % 10;
if (l != r) return false;
x = (x % div) / 10;
div /= 100;
}
return true;
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：1172603次
• 积分：13238
• 等级：
• 排名：第992名
• 原创：408篇
• 转载：14篇
• 译文：0篇
• 评论：138条
博客专栏
 LeetCode(C++) 文章：47篇 阅读：98039
阅读排行
最新评论