标签:
1 题目:
Determine whether an integer is a palindrome. Do this without extra space.
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.
public boolean isPalindrome(int x) { if(x < 0){ return false; } if(x == 0) return true; int len = 1; int temp = x; while( temp / 10 != 0){ len++; temp = temp / 10; } int front = 1; int rear = len; temp = x; while(front < rear){ int numFront = pow10(rear); int numRear = (front-1==0) ? temp%10 : temp/(pow10(front))%10; if(((temp/numFront)%10) != numRear){ return false; }else{ rear--; front++; } } return true; } public int pow10(int rank){ int num = 10; rank = rank - 2; while(rank>0){ num = num *10; rank--; } return num; }
别人思路代码:
public boolean isPalindrome(int x) { if (x < 0) return false; int p = x; int q = 0; while (p >= 10){ q *=10; q += p%10; p /=10; } return q == x / 10 && p == x % 10; }
标签:
原文地址:http://www.cnblogs.com/lingtingvfengsheng/p/4559097.html