Position of rightmost set bit in C++


In this problem, we are given a number N. Our task is to print the index of the rightmost set bit of the number.

Let’s take an example to understand the problem,

Input − 4

Output − 3

Explanation − binary of 4 is 100, the index of the rightmost set bit is 3.

To solve this problem, a simple solution would be shifting the number till a set bit is encountered but this could take a lot of computation if the number is large.

A more efficient solution will be using boolean algebra. For this we will first calculate 2’s complement of the number, this will flip all bits of the number leaving the first set bit as it is. Then we will compute bit-wise & of the number and it’s 2’s complement. This will result in a number with only one set bit and the position we want. The solution will be given by log2 of the number +1.

This seems a bit complex to understand let’s solve an example using this method.

N= 10 , binary = 1010
2’s complement, 0101
1010 & 0101 = 0010
log2(2) = 1
1+1 = 2 which is the given index.

Example

Program to show the implementation of our solution,

 Live Demo

#include <iostream>
#include <math.h>
using namespace std;
void rightSetBit(int N) {
   int bitIndex = log2(N & -N)+1;
   cout<<bitIndex;
}
int main() {
   int N = 10;
   cout<<"The rightmost Set bit of the number "<<N<<" is : ";
   rightSetBit(N);
   return 0;
}

Output

The rightmost Set bit of the number 10 is : 2

Updated on: 17-Apr-2020

215 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements