JavaScript水仙花数(传递任意n位数)

时间:2020-07-22 11:39:00   收藏:0   阅读:69

功能:

水仙花数:封装方法,要求传入一个长度N,返回N位数字下所有的水仙花数。所谓的水仙花数是指:一个 n 位数 ( n≥3 ),它的每个位上的数字的 n 次幂之和等于它本身。例如153,370,371,407等都是水仙花数,就拿153来说,153=1*1*1 + 5*5*5 + 3*3*3

拓展要求:不局限于3位数,输入任意n位数,计算出从0~n位数之间的所有水仙花数。

思路:水仙花题型的拓展,将个位的数字先取出,再对十位以后的数组分割,最后进行累加比较。

 1         // /*水仙花数*/
 2         let arr = [];
 3         let n = prompt(‘请输入N位数‘);
 4         for (let num = 0; num <= Math.pow(10, n); num++) {
 5             let i = 0, count = num, sum = 0;
 6             //先执行一次do_while循环
 7             do {
 8                 // 取出个位
 9                 arr[i] = count % 10;
10                 // 去除个位
11                 count = Math.floor(count / 10);
12                 i++;
13             } while (count >= 1)
14 
15             for (let i = 0; i < arr.length; i++) {
16                 //累加
17                 sum += Math.pow(arr[i], arr.length);
18             }
19             if (sum == num) {//如果是水仙花数则返回结果
20                 console.log(num);
21             }
22         }

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!