在 JavaScript 中查找令人困惑的数字


令人困惑的数字

如果数组中的一个数字在垂直和水平方向旋转 180 度后变成另一个也在数组中存在的数字,则该数字令人困惑。例如,如果我们将 6 垂直和水平旋转 180 度,它将变成 9,反之亦然。

我们必须记住,只有 0、1、6、8、9 的旋转才能产生有效的数字。

我们需要编写一个 JavaScript 函数,该函数将自然数 num 作为第一个也是唯一的一个参数。该函数应首先构造一个包含 num 在内的所有自然数(直到 num)的数组。

例如,对于 num = 5,数组应为:

[1, 2, 3, 4, 5]

然后,该函数应该计算数组中存在多少个令人困惑的数字,最后返回该计数。

例如:

如果输入为:

const num = 10;

则输出应为:

const output = 5;

因为数组将是:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],令人困惑的数字是:

1, 6, 8, 9, 10

示例

代码如下:

 在线演示

const num = 10;
const countConfusing = (num = 1) => {
   let count = 0;
   const valid = '01689';
   const rotateMap = {'0': '0', '1': '1', '6': '9', '8': '8', '9': '6'};
   const prepareRotation = num => {
      let res = '';
      const numArr = String(num).split('');
      if(numArr.some(el => !valid.includes(el))){
         return false;
      };
      numArr.map(el => {
         res = rotateMap[el] + res;
      });
      return +res;
   };
   for(let i = 1; i <= num; i++){
      const rotated = prepareRotation(i);
      if(rotated && rotated > 0 && rotated <= num){
         count++;
      };
   };
   return count;
};
console.log(countConfusing(num));

输出

控制台输出将为:

5

更新于:2021年2月27日

190 次浏览

启动您的 职业生涯

完成课程后获得认证

开始
广告
© . All rights reserved.