JavaScript 中的回文数
javascriptweb developmentfront end technologyobject oriented programming
我们需要编写一个 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
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

