你能用javascript給我一個這個解決方案的例子嗎?
檢查這個陣列中哪個數字是冪?arr = [16, 32, 72, 96]
輸出:[16, 32]。因為 16 = 4^2 和 32 = 2^5
這不是關于 2 的冪的解決方案,而是關于 n 的冪。感謝您抽出寶貴時間幫助我!!
uj5u.com熱心網友回復:
怎么樣
arr = [16, 32, 72, 96].filter(
value => Number.isInteger(Math.log2(value))
)
uj5u.com熱心網友回復:
您可以使用自定義布爾函式遍歷元素并在檢查時附加到空陣列。
function isPowerofTwo(n){
return (Math.ceil((Math.log(n) / Math.log(2))))
== (Math.floor(((Math.log(n) / Math.log(2)))));
}
let arr= [16, 32, 72, 96];
let values=[]
for(let i=0;i<arr.length;i ){
if(isPowerofTwo(arr[i])){
values.push(arr[i]);
}
}
console.log(values);
uj5u.com熱心網友回復:
常量數字 = [16, 32, 72, 96];
const power = numbers.filter(isPowerOfTwo);
function isPowerOfTwo(n)
{
if (n == 0)
return 0;
while (n != 1)
{
if (n%2 != 0)
回傳 0;
n = n/2;
}
回傳 1;
}
控制臺日志(電源);
要了解有關此次訪問的更多資訊,請訪問:https : //www.geeksforgeeks.org/program-to-find-whether-a-given-number-is-power-of-2/
uj5u.com熱心網友回復:
我認為它是 2^4 而不是 4^2 我相信你想檢查數字是否是 2 的根 解決方案
let arr=[16,32,72,96];
let i=1;
for(i=1;i<=10;i ){ // this loop will run up to 2^10
let k=Math.pow(2,i);if(k==arr[i-1]){
//do whatever you want to do with the number
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/369123.html
標籤:javascript 数组 数学
上一篇:框中的文本突然出現而不是緩慢顯示
