JavaScript中的回文数
我们需要编写一个接受数字并确定其是否为回文数的JavaScript函数。
回文数-回文数是从左侧和右侧读取相同的数字。
例如-
343是回文数
6789876是回文数
456764不是回文数
示例
为此的代码将是-
const num1 = 343;
const num2 = 6789876;
const num3 = 456764;
const isPalindrome = num => {
let length = Math.floor(Math.log(num) / Math.log(10) +1);
while(length > 0) {
let last = Math.abs(num − Math.floor(num/10)*10);
let first = Math.floor(num / Math.pow(10, length −1));
if(first != last){
return false;
};
num −= Math.pow(10, length−1) * first ;
num = Math.floor(num/10);
length −= 2;
};
return true;
};
console.log(isPalindrome(num1));
console.log(isPalindrome(num2));
console.log(isPalindrome(num3));输出结果
控制台中的输出将是-
true true false