Position of right most set bit

Problem Link

2's complement flips every bit except right most 1.

Hence AND operation with n and its two's complement will give 2 power position of rightmost 1. We can get position by taking log.

Code:

package bitManipulation;

public class RightMostSetBit {
   
    public static void main(String[] args){
       
        int n = 12;
        int rightmostbit;
       
        rightmostbit = (int) (Math.log10((n & -n)) / Math.log10(2)) +1;
       
        System.out.print(rightmostbit);
       
       
    }

}


Output:

3


Comments

Popular posts from this blog

Rearrange Array in Maximum-Minimum form

Second Largest Element

Check if a number is a power of another number