判断输入的数值是否是2的整数次幂?
判断输入的数值是否是2的整数次幂
isPowerOfTwo(8);
isPowerOfTwo(5);
算法的突破口:
用2区分解输入的数字以及被分解出来的结果,直到得到的商为1,
并且判断它的玉树是否为0
while循环实现 isPowerOfTwo
function isPowerOfTwo(number) {
if (number < 1) {
return false;
}
let dividedNumber = number;
while (dividedNumber !== 1) {
if (dividedNumber % 2 !== 0) {
return false;
}
dividedNumber = dividedNumber / 2;
}
return true;
}
使用按位与运算-性能优化
function isPowerOfTwo(number) {
if (number < 1) {
return false;
}
return (number & (number - 1)) === 0;
}
console.log('isPowerOfTwo(3)', isPowerOfTwo(3));
console.log('isPowerOfTwo(4)', isPowerOfTwo(4));
console.log('isPowerOfTwo(5)', isPowerOfTwo(5));
console.log('isPowerOfTwo(8)', isPowerOfTwo(8));
console.log('isPowerOfTwo(9)', isPowerOfTwo(9));
console.log('isPowerOfTwo(12)', isPowerOfTwo(12));
console.log('isPowerOfTwo(13)', isPowerOfTwo(13));