原题:
Determine whether an integer is a palindrome. Do this without extra space.
» Solve this problem
方法:
建立一个辅助因子,最高位为一,其余为零,位数和原数值相同。利用辅助因子对数值进行从外到里的扫描,扫描完毕,原值改为:原值对辅助因子取模并除以十;辅助因子缩小100倍。
代码:
public class Solution {
public boolean isPalindrome(int x) {
// Start typing your Java solution below
// DO NOT write main() function
if(x < 0) return false;
int div = 10;
while(x/div > 9)
div *= 10;
while(x > 9){
if(x/div != x%10)
return false;
x = x % div / 10;
div /= 100;
}
return true;
}
}
小结:
看似一道回文题,考的数字位数的技巧。