Determine whether an integer is a palindrome. Do this without extra space.
思路:
不能用额外空间,所以不能将数字转换成字符串再判断,那就一步步的对整数进行取余和取整来获得想要的数字。比如1221,1221/1000就取得首位1,1221%10就得到末尾1,接下来将整数变成22((x%1000)/10)。直到x<=0时停止循环。最开始的1000通过while循环获得。
var isPalindrome = function(x) {
if(x<0) return false;
var div=1;
while(Math.floor(x/div)>=10) div*=10;
console.log(div)
while(x>0){
var left=Math.floor(x/div);
var right=x%10;
if(left!=right) return false;
x=Math.floor((x%div)/10);
div/=100;
}
return true;
};
注意js的/不是取整,要用Math.floor()来获得取整后的数。