Power of Two Checks
In this approach, we are Checking if a number is a power of two using bitwise AND of num and (num – 1).
Syntax:
function isPowerOfTwo(num) {
return (num & (num - 1)) === 0 && num > 0;
}
Example: In this example, we are using the above-explained approach.
Javascript
function GFG(num) { if (num <= 0) { return false ; } while (num > 1) { if (num % 2 !== 0) { return false ; } num /= 2; } return true ; } console.log(GFG(16)); console.log(GFG(9)); |
true false
Bit manipulation in JavaScript
Bit manipulation in JavaScript refers to the manipulation and operation of individual bits within binary representations of numbers and JavaScript uses 32-bit signed integers for numeric values. It involves using bitwise operators (&, |, ^, ~, <<, >>) to manipulate individual bits of binary numbers. These operations can be used for bitwise logic operations such as AND, OR, XOR, and shifting bits.
Below is a list of bitwise operators:
- Bitwise AND(&): Returns true if both operands are true.
- Bitwise OR(|): Returns true even if one operand is true.
- Bitwise XOR(^): Returns true if both operands are different.
- Bitwise NOT(~): Flips the value of the operand.
- Bitwise Left Shift(<<): Shifts the bit toward the left.
- Bitwise Right Shift(>>): Shifts the bit towards the right.
- Zero Fill Right Shift(>>>): Shifts the bit towards the right but adds 0 from the left.
Below we will describe the common bit manipulation problems in detail:
Table of Content
- Checking Odd or Even
- Swap Two Numbers
- Finding the Single Odd Occurrence
- Power of Two Checks
- Count Total Bits Set