Power of 2
FIRST SOLUTION
let n = 64;
//Solution :-1
while (n !== 1) {
let rem = n % 2;
if (rem === 0) {
n = n / 2;
if (n === 2) {
console.log("Number is power of 2");
break;
}
} else {
console.log("Number is not power of 2");
break;
}
}
let number1 = 32;
let number2 = 31;
console.log(number1.toString(2));
console.log(number2.toString(2));
SECOND SOLUTION
& operator is O(1)
//Solution :-2
let number2 = 32;
let number1=number2-1;//31
let output = number2 & number1;
if (output === 0)
console.log("Number is power of 2");
else console.log("Number is not power of 2");
// number1-32
// number2-31
// 100000
// * 011111
// --------
// 000000
// --------
// number1-34
// number2-33
// 100010
// * 100001
// --------
// 100000
// --------