![]() |
VOOZH | about |
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.
Table of Content
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.
2
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.
2
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.
2
2