w3resource

JavaScript - Position of the rightmost set bit of a number

JavaScript Bit Manipulation: Exercise-12 with Solution

Write a JavaScript program to find the position of the rightmost set bit of a given number. Set bits in a binary number is represented by 1.

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:

const turn_On_Kth_Bit = (n, k) => {
 if (typeof n!= "number") {
     return 'It must be number!'
     }
   if ((n & 1) != 0) {
            return 1;
        }
   n = n ^ (n & (n - 1));
   pos = 0;
   while (n != 0)
     {
       n = n >> 1;
       pos++;
      }
 
  return pos;
 }

n = 34
console.log(n + " in binary is " + n.toString(2))
position = turn_On_Kth_Bit(n);
console.log("Position of the rightmost set bit of the said number: " + position)
 
n = 104
console.log(n + " in binary is " + n.toString(2))
position = turn_On_Kth_Bit(n);
console.log("Position of the rightmost set bit of the said number: " + position)

Sample 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:

Flowchart: JavaScript - Position of the rightmost set bit of a number.

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.



Follow us on Facebook and Twitter for latest update.

JavaScript: Tips of the Day

Returns the symmetric difference between two arrays, after applying the provided function to each array element of both

Example:

const tips_symmetricDifference = (x, y, fn) => {
  const sA = new Set(x.map(v => fn(v))),
    sB = new Set(y.map(v => fn(v)));
  return [...x.filter(x => !sB.has(fn(x))), ...y.filter(x => !sA.has(fn(x)))];
};

console.log(tips_symmetricDifference([3.5, 5.5], [5.5, 7.5], Math.floor));

Output:

[3.5, 7.5]