【问题标题】:Writing a function that takes an integer as input, and returns number of bits to binary编写一个将整数作为输入的函数,并将位数返回为二进制
【发布时间】:2019-06-27 01:50:36
【问题描述】:

我正在进行代码战练习,但它不接受我的解决方案,并引发类型错误:无法读取 null 的属性“长度”。我在一个单独的 Chrome 窗口中检查了我的代码,它运行良好。当使用任何整数调用该函数时,我会从二进制数中得到所有的 1。我做错了什么?

var countBits = function(n) {
  var result = n.toString(2).match(/1/g).length;
  return result;
};

【问题讨论】:

  • 用零试试。

标签: javascript arrays regex function


【解决方案1】:

如果你在函数中输入的字符不匹配,你应该添加条件来检查null。

var result = n.toString(2).match(/1/g) != null ? n.toString(2).match(/1/g).length : 0;

var countBits = function(n) {
  var result = n.toString(2).match(/1/g) != null ? n.toString(2).match(/1/g).length : 0;
  return result;
};
console.log(countBits('a'))

【讨论】:

    【解决方案2】:

    如果字符串与您的正则表达式不匹配,这将返回错误。做这样的事情。

    var countBits = function(n) {
      var result = n.toString(2).match(/1/g);
      if (result){       
          return result.length;
      }
      return 0;
    };
    

    【讨论】:

      【解决方案3】:

      如果没有 1 (0),match 将返回 null。你可以改用filter

      const countBits = n => [...n.toString(2)].filter(e => e === "1").length;
      

      【讨论】:

      • 固定@Ry-,更好吗?
      【解决方案4】:

      虽然将数字转换为字符串并使用正则表达式进行计数并没有什么问题,但您也可以通过简单的数学来做到这一点——只需连续除以 2 并查看数字 mod 2 直到将其减少到零。

      var countBits = function(n) {
         let s = 0;
         while (n > 0){
           s += n % 2
           n = Math.floor(n/2)
        }
        return s
      };
      
      console.log(countBits(0))
      console.log(countBits(2))
      console.log(countBits(3))
      console.log(countBits(1234))

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-10-18
        • 2020-05-31
        • 2020-11-09
        • 2020-10-30
        • 1970-01-01
        • 1970-01-01
        • 2023-03-14
        相关资源
        最近更新 更多