查找数字中的闭环-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