Javascript 确定给定数字是否为二的幂的最佳方法是什么?

Javascript 确定给定数字是否为二的幂的最佳方法是什么?,javascript,Javascript,如果n是2的幂,我需要返回true,否则返回false。应该是这样的: function PowerOfTwo(n){ //code here } 这就是我目前的做法: function isPowerOfTwo(n){ var x = Math.pow(2, Math.round(Math.log(n) / Math.log(2))); return x; } 还有更有效的方法吗?来源: 您只需按位将上一个数字与当前数字相加。如果结果是falsy,那么它是2的幂 这个解释是正确

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

function PowerOfTwo(n){
  //code here
}
这就是我目前的做法:

function isPowerOfTwo(n){
  var x = Math.pow(2, Math.round(Math.log(n) / Math.log(2)));
  return x;
}
还有更有效的方法吗?

来源:

您只需按位将上一个数字与当前数字相加。如果结果是falsy,那么它是2的幂

这个解释是正确的

注:

  • 对于编程、数学[也可以阅读“面试”]来说,这并不是100%正确的。一些边缘情况不由此处理,它们是小数(0.1、0.2、0.8…)或零值(0、0.0…)

您实际上可以使用ECMAScript 5
Math.log

function powerOfTwo(x) {
    return (Math.log(x)/Math.log(2)) % 1 === 0;
}
请记住,在数学中,要获得具有任意基数的对数,只需将操作数的log10(
x
在本例中)除以基数的log10即可。然后,要查看该数字是否为正则整数(而不是浮点),只需使用模
%
运算符检查余数是否为0

在ECMAScript 6中,可以执行以下操作:

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

有关使用位运算符的
Math.log2
,请参见,这是迄今为止代码效率和清洁度方面最好的方法:

function PowerofTwo(n){
    return ((x != 0) && !(x & (x - 1)));
}
它所做的是检查组成数字的位,即8如下所示:

function powerOfTwo(x) {
    return Math.log2(x) % 1 === 0;
}
1 0 0 0
 0 1 1 1
-0 1 1 0
=========
 1 1 1 0
x-1
或7在本例中看起来像这样

0 1 1 1
当使用逐位运算符
&
时,它在数字的每个位上调用一个&&(因此
1&1=1
1&0=0
0&1=0
0&0=1
):

因为使用
将数字转换为精确的0(或作为布尔值计算时为false)标志将返回正确答案

如果你用一个像7这样的数字来做这件事,它会是这样的:

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

返回一个大于零的数字,导致
标志接管并给出正确答案。

当且仅当该数字的对数基数2为整数时,该数字为2的幂。下面的函数计算这是否为真:

function PowerOfTwo(n){
  // Exercise for reader: confirm that n is an integer
  return (n !== 0) && (n & (n - 1)) === 0;
}
function powerOfTwo(n){
    // Compute log base 2 of n using a quotient of natural logs
    var log_n = Math.log(n)/Math.log(2);
    // Round off any decimal component
    var log_n_floor = Math.floor(log_n);
    // The function returns true if and only if log_n is a whole number
    return log_n - log_n_floor == 0; 
}
利用ES6计算从1到2-1的32位整数的前导零:

function isPowerOf2(n) {
  return Math.clz32(n) < Math.clz32(n - 1);
}
函数ispowerrof2(n){
返回Math.clz32(n)
/**
*@param{number}n
*@return{boolean}
*/
const isPowerOfTwo=函数(n){
如果(n==0)返回false;
而(n%2==0){
n=n/2
}
返回n==1

};returnx==n谢谢,有时候我的想法很模糊,我无法逻辑地思考
返回(Math.log(n)/Math.log(2))%1==0
好,我给你投票;)也给我一个提示?
(x!=0)
x
相同。因此,你的答案与“thefourtheye”相同s@blex:错了<代码>x!=0
x
转换为一个数字,只需使用
x
即可将其转换为布尔值。差别很大!不过,答案是不必要的。@FelixKling当然,我的意思是,在这种情况下,它没有什么区别,因为
0
false
都是假值,而任何其他整数和
true
都是真值!(n&n-1)
好的解释不能涵盖消极的tho<代码>返回(x>0)&((x!=0)&!(x&(x-1))