javascript - 如何在不使用 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
,而不使用更原始的操作?哪种方式表现更好?
解决方案
我们可以计算一个数字中的位数 - 这将是 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))));
推荐阅读
- objective-c - 制作按钮时传递和使用选择器的问题
- tensorflow - 尽管使用了 tf 数据管道,但训练速度很慢
- jsx - 如何解决意外字符 '�' (1:0) 错误
- r - 如何在 R 中的 acf() 路由中使用“一组滞后(时差)来保留”
- python - ValueError: numpy.ndarray 大小在导入 qiskit 时更改
- android - Android Studio - Kotlin - 添加一个可点击的小型谷歌地图
- c# - 迁移不适用于 ON CASCADE DELETE 行为的所有外键
- python - 在单个 SQLAlchemy 查询中选择函数和表列
- python - Python:按下按钮时主窗口关闭
- dart - 在 Dart 中:我想打印一个前面有一个字符串的 Setter(一个 int),例如: Car age: 7 years