Take a Number And Sum Its Digits Raised To The Consecutive Powers And ….¡Eureka!!

题目

The number 89 is the first integer with more than one digit that fulfills the property partially introduced in the title of this kata. What’s the use of saying “Eureka”? Because this sum gives the same number.

In effect: 89 = 8^1 + 9^2

The next number in having this property is 135.

See this property again: 135 = 1^1 + 3^2 + 5^3

We need a function to collect these numbers, that may receive two integers a, b that defines the range [a, b] (inclusive) and outputs a list of the sorted numbers in the range that fulfills the property described above.

Let’s see some cases:

1
2
3
4
5
6
sumDigPow(1, 10) == [1, 2, 3, 4, 5, 6, 7, 8, 9]

sumDigPow(1, 100) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 89]
If there are no numbers of this kind in the range [a, b] the function should output an empty list.

sumDigPow(90, 100) == []

Enjoy it!!

思路

  • for循环检查每个数字
  • 数字转换成数组
  • 使用数组的reduce方法对数组里的每一位进行运算
  • 构建reduce方法使用的函数
  • 幂运算符** 2**3 = 2^3
reduce()
语法
currentValue, currentIndex, arr), initialValue)```
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
- total 初始值/函数返回值
- currentValue 当前值
- currentIndex 当前index位置
- arr 当前数组
- initialValue 函数的初始值

#### 答案
```javascript
function sumDigPow(a, b) {
var arr = new Array();

function calc(total, c_Value, c_Index) {
return total + c_Value ** (c_Index + 1);
}

for (var i = a; i < b; i++) {
var digi = String(i).split("");
if (i == digi.reduce(calc, 0)) {
arr.push(i);
}
}
return arr;
}
答案解析

首先定义了一个函数calc,函数有三个参数,分别是和,当前值,当前数组的位置。
按照题目要求的方法对每一位进行计算,然后加上当前的和。
reduce()方法会遍历数组里的每一项进行计算求和,reduce()方法的两个参数,第一个是函数,第二个是函数的初始值(也就是最初的total是0)。