Palindrome Number

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)  这里负数返回false

If you are thinking of converting the integer to string, note the restriction of using extra space.  //itoa

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?  //long long 保存中间变量

There is a more generic way of solving this problem.

 

思路:从后计数,得到的结果和原数一致

java代码:

public boolean isPalindrome(int x) {
boolean sign = x>0 ? true : false;
if(x==0) return true;
if(!sign) return false;
int base = 0;
int init = x;
while(x!=0) {
base = base * 10 + x % 10;
x /= 10;
}
if(base == init) return true;
return false;
}

posted @ 2014-07-28 00:29  purejade  阅读(110)  评论(0编辑  收藏  举报