![](/img/trans.png)
[英]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.