programming-examples/js/Math/Test if a number is a power of 2.js

10 lines
240 B
JavaScript
Raw Normal View History

2019-11-15 12:59:38 +01:00
function power_of_2(n) {
if (typeof n !== 'number')
return 'Not a number';
return n && (n & (n - 1)) === 0;
}
console.log(power_of_2(16));
console.log(power_of_2(18));
console.log(power_of_2(256));