Position of rightmost set bit

Write a one line C function to return position of first 1 from right to left, in binary representation of an Integer.

I/P    18,   Binary Representation 010010
O/P   2
I/P    19,   Binary Representation 010011
O/P   1



Algorithm: (Example 18(010010))
Let I/P be 12 (1100)

1. Take two's complement of the given no as all bits are reverted
except the first '1' from right to left (10111)

2  Do an bit-wise & with original no, this will return no with the
required one only (00010)

3  Take the log2 of the no, you will get position -1 (1)

4  Add 1 (2)

Program:

C

#include<stdio.h>
#include<math.h>

unsigned int getFirstSetBitPos(int n)
{
   return log2(n&-n)+1;
}

int main()
{
    int n = 12;
    printf("%u", getFirstSetBitPos(n));
    getchar();
    return 0;
}

Java

// Java Code for Position of rightmost set bit
class GFG {
    
    public static int getFirstSetBitPos(int n)
    {
       return (int)((Math.log10(n & -n)) / Math.log10(2)) + 1;
    }
    
    // Drive code
    public static void main(String[] args) 
    {
        int n = 12;
        System.out.println(getFirstSetBitPos(n));
           
    }
 }
  // This code is contributed by Arnav Kr. Mandal

Python3

# Python Code for Position
# of rightmost set bit

import math

def getFirstSetBitPos(n):

     return math.log2(n&-n)+1

# driver code

n = 12
print(int(getFirstSetBitPos(n)))

# This code is contributed
# by Anant Agarwal.

C#

// C# Code for Position of rightmost set bit
using System;

class GFG
{
    public static int getFirstSetBitPos(int n)
    {
        return (int)((Math.Log10(n & -n)) / Math.Log10(2)) + 1;
    }
    
    // Driver method
    public static void Main() 
    {
        int n = 12;
        Console.WriteLine(getFirstSetBitPos(n));
    }
}

// This code is contributed by Sam007


Output:

3

Asked in: Amazon




Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



2.7 Average Difficulty : 2.7/5.0
Based on 66 vote(s)