面试题:判断一个数是否是2的整数次幂
面试题:判断一个数是否是2的整数次幂
- 暴力破解
// 暴力破解,时间复杂度O(log(n))
function isPowerOf2(val) {
let temp = 1;
while (temp <= val) {
if (temp === val) {
return true;
}
temp = temp * 2;
}
return false;
}
console.log(isPowerOf2(123));
console.log(isPowerOf2(12234));
- 位移运算,时间复杂度O(log(n))
function isPowerOf2V2(val) {
let temp = 1;
while (temp <= val) {
if (temp === val) {
return true;
}
temp = temp << 1;
}
return false;
}
console.log(isPowerOf2V2(123));
console.log(isPowerOf2V2(12234));
- 位运算 时间复杂度O(1)
function isPowerOf2V3(val) {
return (val & (val - 1)) === 0;
}
console.log(isPowerOf2V3(8));
console.log(isPowerOf2V3(12234));
本文来自博客园,作者:struggle_time,转载请注明原文链接:https://www.cnblogs.com/songliquan/p/13073302.html