Leetcode c语言-Palindrome Number
Title:
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.
bool isPalindrome(int x) {
int i,m,n,p,q;
int result;
int temp;
if (x<0)
return 0;
for (i=10;i>=1;i--) {
temp =x/(pow(10,i-1));
if (temp)
break;
}
if (i==1) /*一个数字*/
return 1;
if (i%2 == 0) {
m = i/2;
n = i/2 + 1;
while (m>=1) {
p = x/pow(10,m-1);
q = x/pow(10,n-1);
if (p%10 != q%10) {
result = 0;
break;
}
else
result = 1;
m--;
n++;
}
}
else if (i%2 != 0) {
m = i/2;
n = i/2 +2;
while (m>=1) {
p = x/pow(10,m-1);
q = x/pow(10,n-1);
if (p%10 != q%10) {
result = 0;
break;
}
else
result =1;
m--;
n++;
}
}
return result;
}
posted on 2017-09-11 14:23 sichenzhao 阅读(122) 评论(0) 编辑 收藏 举报