如果n是2的幂,我需要返回true,否则返回false.它应该是这样的:
function PowerOfTwo(n){
//code here
}
Run Code Online (Sandbox Code Playgroud)
这是我目前的方式:
function isPowerOfTwo(n){
var x = Math.pow(2, Math.round(Math.log(n) / Math.log(2)));
return x;
}
Run Code Online (Sandbox Code Playgroud)
有没有更有效的方法?
the*_*eye 16
资料来源:比特杂乱的黑客,
function powerOf2(v) {
return v && !(v & (v - 1));
}
Run Code Online (Sandbox Code Playgroud)
你只需用当前数字按位和前一个数字.如果结果是假的,那么它是2的幂.
这个答案就是解释.
你可以实际使用ECMAScript5 Math.log:
function powerOfTwo(x) {
return (Math.log(x)/Math.log(2)) % 1 === 0;
}
Run Code Online (Sandbox Code Playgroud)
请记住,在数学中,要获得具有任意基数的对数,您只需将操作数的log 10(x在本例中)除以基数的log 10即可.然后,要查看该数字是否是常规整数(而不是浮点数),只需使用模数%运算符检查余数是否为0 .
在ECMAScript6中,您可以执行以下操作:
function powerOfTwo(x) {
return Math.log2(x) % 1 === 0;
}
Run Code Online (Sandbox Code Playgroud)
见MDN文档的Math.log2.
| 归档时间: |
|
| 查看次数: |
3532 次 |
| 最近记录: |