在 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 ]
廣告