![]() |
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:
Below we will describe the common bit manipulation problems in detail: Table of ContentChecking Odd or EvenIn this approach, we are using bitwise AND (&) to check the least significant bit of n. If it’s set (odd), “odd” is printed; otherwise, “even” is printed. Syntax:if (num & 1) {
// num is odd
} else {
// num is even
} Example: In this example, we are using the above-explained approach.
Output 8 is even. Swap Two NumbersIn this approach we Swap two variables using bitwise XOR by applying XOR twice to each variable, cancelling out the effect and achieving the swap without extra storage. Syntax:a = a ^ b;
b = a ^ b;
a = a ^ b; Example: In this example, values of a and b are swapped using XOR. The original values are exchanged without a temporary variable.
Output a: 10 b: 8 Finding the Single Odd OccurrenceUsing XOR, iterate through an array where elements appear twice except one. XOR cancels pairs, leaving the odd-occurrence element. Syntax:let result = 0;
for (let num of nums) {
result ^= num;
} Example: In this example, XOR array elements, cancel pairs, and find an element occurring once.
Output element that occurs only once: 12 Power of Two ChecksIn 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.
Output true false Count Total Bits SetIn this approach, we Count the total set bits in a number using a loop with bitwise AND operation and right shift. Syntax: function countSetBits(num) {
let count = 0;
while (num) {
count += num & 1;
num >>= 1;
}
return count;
} Example: Here we are using the above-explained approach.
Output 3 3 |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |