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
广告
数据结构
网络
关系型数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C #
MongoDB
MySQL
JavaScript
PHP