![]() |
We are given an integer value, the task is to extract the rightmost set bit of a given integer in JavaScript. The rightmost set bit is the bit whose value is 1 and appears first when reading the binary representation of a number from right to left. The below approaches can be used to find the rightmost set bit in JavaScript. Table of Content Using Bitwise OperationsIn this approach, we are using the bitwise AND (&) operator with the negation of the input number to isolate the rightmost set bit, effectively extracting it. This works because -num creates a number with only the rightmost set bit of num preserved, allowing the AND operation to capture just that bit. Syntax:num & -num Example: The below example uses Bitwise Operations to extract the rightmost set bit of a given integer in JavaScript.
Output 6 Using Bitwise XOR and ComplementIn this approach, we are using bitwise XOR (^) and a combination of bitwise AND (&) with subtraction (num – 1) to extract the rightmost set bit of the input number num. The expression (num & (num – 1)) effectively clears all bits to the right of the rightmost set bit, leaving only that bit intact for the XOR operation to isolate it. Syntax:let result = operand1 ^ operand2; Example: The below example uses Bitwise Operations to extract the rightmost set bit of a given integer in JavaScript.
Output 4 Using Bitwise Shift and LoopIn this approach, we are using bitwise left shift (<<) in a loop to create a mask that isolates the rightmost set bit of the input number num. The loop iteratively shifts the mask to the left until it aligns with the rightmost set bit in num, which is then extracted using the bitwise AND (&) operation. Syntax:while(condition) { Example: The below example uses Bitwise Operations to extract the rightmost set bit of a given integer in JavaScript.
Output 6 |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 15 |