VOOZH about

URL: https://www.geeksforgeeks.org/dsa/position-of-rightmost-set-bit/

⇱ Position of rightmost set bit - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Position of rightmost set bit

Last Updated : 5 Feb, 2026

Given an integer n, Return the position of the first set bit from right to left in the binary representation n. If no set bits present , then return 0.
Note: Position of rightmost bit is 1.

Examples:

Input: n = 18
Output: 2
Explanation: Binary representation of 18 is 10010, hence position of first set bit from right is 2.

Input:  n = 19
Output: 1
Explanation: Binary representation of 19 is 10011, hence position of first set bit from right is 1.

Using 2's complement and log Operator - O(log n) time and O(1) space

The idea is to find the rightmost set bit using a property of 2's complement arithmetic. When we perform n & (~n + 1) or equivalently n & (-n), we get a number with only the rightmost set bit of n. Then we can use log2 to find its position.


Output
2

Using left shift operator - O(1) time and O(1) space

The idea is to use a counter and iteratively left-shift 1 to check each bit position. Increment a position counter until we find a bit that is set.


Output
2

Using right shift operator - O(1) time and O(1) space

The idea is to right-shift the number and check the least significant bit in each iteration. Increment a position counter until we find a bit that is set.


Output
2

Using Built-In Library Functions - O(1) time and O(1) space


Output
2


Comment
Article Tags:
Article Tags: