首页 > 解决方案 > 如何在不使用 JavaScript 中的 Math.log 的情况下获得指数“x”(2 的“x”次方)?

问题描述

到目前为止我有这个(这都是按位的,不使用Math函数):

function nextPowerOf2(n) {  
  if (n && !(n & (n - 1))) {
    return n
  }

  let p = 1
  while (p < n) {
    p <<= 1
  }
  
  return p  
}  

不过,要获得指数,我必须这样做:

const exp = Math.log2(nextPowerOf2(val))

有没有办法做到这一点Math.log,而不使用更原始的操作?哪种方式表现更好?

标签: javascriptmathbit-manipulation

解决方案


我们可以计算一个数字中的位数 - 这将是 log2(nextPowerOf2):

const log2ofNextPowerOf2 = (x) => {
  if (!x) return 0;
  let c = 0, b = 0;
  while (x > 0) {
    c++; b += x & 1;
    x = x >> 1;
  }
  return b == 1 ? c - 1 : c;
}

// test it:
[0, 1, 2, 3, 4, 5, 8, 100].forEach(n => console.log(n, '=>', log2ofNextPowerOf2(n)));

将此与您的原始功能进行比较:

function nextPowerOf2(n) {
  if (n && !(n & (n - 1))) {
    return n
  }
  let p = 1
  while (p < n) {
    p <<= 1
  }

  return p
}

// test it:
[0, 1, 2, 3, 4, 5, 8, 100].forEach(n => console.log(n, '=>', Math.log2(nextPowerOf2(n))));


推荐阅读