在 JavaScript 中找到某个范围内阿姆斯特朗数
如果一个数满足以下方程式,则该数称为阿姆斯特朗数:xy...z = xx + yy + ... + zz,其中 n 表示数字中的位数。
例如
153 是一个阿姆斯特朗数因为 −
11 +55 +33 = 1 + 125 + 27 =153
我们需要编写一个 JavaScript 函数,该函数接受两个数字(一个范围),并返回介于这两个数字之间的所有阿姆斯特朗数(包括这两个数字(如果它们是阿姆斯特朗数))。
示例
代码将是 −
const isArmstrong = number => {
let num = number;
const len = String(num).split("").length;
let res = 0;
while(num){
const last = num % 10;
res += Math.pow(last, len);
num = Math.floor(num / 10);
};
return res === number;
};
const armstrongBetween = (lower, upper) => {
const res = [];
for(let i = lower; i <= upper; i++){
if(isArmstrong(i)){
res.push(i);
};
};
return res;
};
console.log(armstrongBetween(1, 400));输出
控制台中的输出 −
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371 ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP