- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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,

#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

- Related Articles
- Position of rightmost different bit in C++
- Golang Program to find the position of the rightmost set bit
- Position of rightmost common bit in two numbers in C++
- Position of rightmost bit with first carry in sum of two binary in C++
- Find position of the only set bit in C++
- Python Program to Clear the Rightmost Set Bit of a Number
- Position of the K-th set bit in a number in C++
- Set the bit at a specific position in the BitArray to the specified value in C#?
- Check whether the bit at given position is set or unset in Python
- Get value of the bit at a specific position in BitArray in C#
- Find most significant set bit of a number in C++
- Find position of left most dis-similar bit for two numbers in C++
- Find letter's position in Alphabet using Bit operation in C++
- Program to check we can reach leftmost or rightmost position or not in Python
- Update the bit in the given position or Index of a number using C++