在數字中查詢封閉迴路 - JavaScript
0、4、6、8、9 這些數字除了都是自然數之外,還有一個共同點。這些數字都由其形狀中至少一個封閉迴路形成或包含一個封閉迴路。
例如,數字 0 是封閉迴路,8 包含兩個封閉迴路,4、6、9 各包含一個封閉迴路。
我們需要編寫一個 JavaScript 函式,它接收一個數字,並返回其所有數字中封閉迴路的總和。
例如,如果數字為 4789
則輸出應為 4,即
1 + 0 + 2 + 1
示例
以下為程式碼 −
const num = 4789;
const calculateClosedLoop = (num, {
count,
legend
} = {count: 0, legend: {'0': 1, '4': 1, '6': 1, '8': 2, '9': 1}}) => {
if(num){
return calculateClosedLoop(Math.floor(num / 10), {
count: count + (legend[num % 10] || 0),
legend
});
};
return count;
};
console.log(calculateClosedLoop(num));輸出
以下為控制檯中的輸出 −
4
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP