JavaScript - Position of the rightmost set bit of a number
JavaScript Bit Manipulation: Exercise-12 with Solution
Rightmost Set Bit
Write a JavaScript program to find the position of the rightmost set bit of a given number. The number 1 represents the set bits in a binary number.
Test Data:
(34) -> 2
Explanation:
34 in binary is 100010
Set bits in the 2nd position of the said binary format.
(104) -> 4
Explanation:
104 in binary is 1101000
Set bits in the 4th position of the said binary format.
Sample Solution:
JavaScript Code:
// Define a function to find the position of the rightmost set bit in a number
const turn_On_Kth_Bit = (n, k) => {
// Check if the input is not a number
if (typeof n != "number") {
return 'It must be number!'; // Return an error message
}
// Check if the rightmost bit is already set
if ((n & 1) != 0) {
return 1; // Return the position 1
}
// Find the position of the rightmost set bit
n = n ^ (n & (n - 1)); // Remove all bits except the rightmost set bit
let pos = 0; // Initialize the position variable
while (n != 0) {
n = n >> 1; // Right shift n by 1 bit
pos++; // Increment the position
}
return pos; // Return the position of the rightmost set bit
}
// Initialize variable n with a value
let n = 34;
// Display the binary representation of n
console.log(n + " in binary is " + n.toString(2));
// Call the turn_On_Kth_Bit function to find the position of the rightmost set bit
let position = turn_On_Kth_Bit(n);
// Display the position of the rightmost set bit
console.log("Position of the rightmost set bit of the said number: " + position);
// Update variable n with a new value
n = 104;
// Display the binary representation of n
console.log(n + " in binary is " + n.toString(2));
// Call the turn_On_Kth_Bit function to find the position of the rightmost set bit
position = turn_On_Kth_Bit(n);
// Display the position of the rightmost set bit
console.log("Position of the rightmost set bit of the said number: " + position);
Output:
34 in binary is 100010 Position of the rightmost set bit of the said number: 2 104 in binary is 1101000 Position of the rightmost set bit of the said number: 4
Flowchart:
Live Demo:
See the Pen javascript-bit-manipulation-exercise-12 by w3resource (@w3resource) on CodePen.
* To run the code mouse over on Result panel and click on 'RERUN' button.*
Improve this sample solution and post your code through Disqus.
Previous: Check if kth bit is set or not for a number.
Next: Parity of a given number.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics