[英]What is the best way to determine the number of business days between two dates in JavaScript?
[英]What is the best way to determine if a given number is a power of two?
如果 n 是 2 的幂,我需要返回true ,否则返回false 。 它应该 go 类似于:
function PowerOfTwo(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;
}
请记住,在数学中,要获得具有任意底数的对数,您只需将操作数的 log 10 (在本例中为x
)除以底数的 log 10 。 然后要查看该数字是否为常规整数(而不是浮点数),只需使用模数%
运算符检查余数是否为 0。
在 ECMAScript6 中,您可以执行以下操作:
function powerOfTwo(x) {
return Math.log2(x) % 1 === 0;
}
请参阅Math.log2
的MDN 文档。
资料来源: Bit twiddling Hacks ,
function powerOf2(v) {
return v && !(v & (v - 1));
}
您只需将前一个数字与当前数字按位 AND 即可。 如果结果为假,则为 2 的幂。
解释在这个答案中。
笔记:
使用按位运算符,这是迄今为止代码效率和清洁度的最佳方法:
function PowerofTwo(n){
return ((x != 0) && !(x & (x - 1)));
}
它所做的是检查组成数字的位,即 8 看起来像这样:
1 0 0 0
在这种情况下x-1
或 7 看起来像这样
0 1 1 1
当使用按位运算符&
时,它会在数字的每一位上调用 && (因此1 & 1 = 1
、 1 & 0 = 0
、 0 & 1 = 0
、 0 & 0 = 1
):
1 0 0 0
-0 1 1 1
=========
0 0 0 0
因为使用!
标志将返回正确答案
如果你用一个像 7 这样的数字来做这个,它看起来像这样:
0 1 1 1
-0 1 1 0
=========
1 1 1 0
返回一个大于零的数字,导致!
旗接管并给出正确答案。
一个数字是 2 的幂当且仅当该数字的对数底 2 是整数。 下面的函数计算这是否为真:
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 的Math.clz32(n)计算从 1 到 2³² - 1 的 32 位整数的前导零:
function isPowerOf2(n) {
return Math.clz32(n) < Math.clz32(n - 1);
}
/** * @param {number} n * @return {boolean} */ const isPowerOfTwo = function(n) { if(n == 0) return false; while(n % 2 == 0){ n = n/2 } return n === 1 };
function PowerOfTwo(n){
// Exercise for reader: confirm that n is an integer
return (n !== 0) && (n & (n - 1)) === 0;
}
不使用库
所以你需要使用 while 创建一个内部循环
它应该从 1 开始,一直乘以 2,直到 i、j、k 或任何大于当前数字(数组)的值,所以它必须做 2 4 6 8 10 12 14 16 18 直到它大于那个数字它将 go 到外循环然后再次重复
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.