Skip to content

Commit e734fcb

Browse files
committed
update Candy-012
1 parent c97705d commit e734fcb

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

Candy-012/README.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
## 編號:CANDY-012
2+
3+
### 程式語言:JavaScript
4+
5+
#### 題目:把數字加總,最終濃縮成個位數
6+
7+
範例:
8+
9+
```js
10+
9527 => 9 + 5 + 2 + 7 => 23 => 2 + 3 => 5
11+
12+
1450 => 1 + 4 + 5 + 0 => 10 => 1 + 0 => 1
13+
```
14+
15+
```js
16+
const numberReducer = (num) => {
17+
while (num >= 10) {
18+
num = [...String(num)].map(Number).reduce((acc, cur) => acc + cur);
19+
}
20+
return num;
21+
};
22+
23+
// 使用 while 迴圈, 將條件設定為 >= 10, 因為只要超過二位數就需要進行一次運算
24+
// 使用展開運算符 (...) 將迴圈的數字透過 String() 轉成字串陣列
25+
// 使用 map() 陣列字串轉成數字, 最後 reduce() 進行加總並回傳
26+
27+
console.log(numberReducer(9527)); // 印出 5
28+
console.log(numberReducer(1450)); // 印出 1
29+
console.log(numberReducer(5566108)); // 印出 4
30+
console.log(numberReducer(1234567890)); // 印出 9
31+
```

0 commit comments

Comments
 (0)