gpt4 book ai didi

javascript - 确定给定数字是否为 2 的幂的最佳方法是什么?

转载 作者:搜寻专家 更新时间:2023-11-01 04:44:16 24 4
gpt4 key购买 nike

如果 n 是 2 的幂,我需要返回 true,否则返回 false。它应该是这样的:

function isPowerOfTwo(n) {
// Code here
}

这是我目前的做法:

function isPowerOfTwo(n) {
var x = Math.pow(2, Math.round(Math.log(n) / Math.log(2)));
return x;
}

有没有更有效的方法?

最佳答案

您实际上可以使用 ECMAScript5 Math.log:

function powerOfTwo(x) {
return (Math.log(x)/Math.log(2)) % 1 === 0;
}

请记住,在数学中,要获得任意底数的对数,只需将操作数(在本例中为 x)的 log10 除以 log10 的基地。然后查看数字是否为常规整数(而不是 float ),只需使用模数 % 运算符检查余数是否为 0。

在 ECMAScript6 中你可以这样做:

function powerOfTwo(x) {
return Math.log2(x) % 1 === 0;
}

参见 MDN docs对于 Math.log2

关于javascript - 确定给定数字是否为 2 的幂的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30924280/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com