# Golang Program to find the position of the rightmost set bit

Go ProgrammingServer Side ProgrammingProgramming

#### Cyber Security : Go from Zero to Hero

Most Popular

60 Lectures 5.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

#### C Programming from scratch- Master C Programming

Best Seller

60 Lectures 8 hours

## Examples

Consider n = 20(00010100)

Now return log2(20 & -20) => 2+1 => 3

Approach to solve this problem

Step 1 − Define a method, where n and is an argument, return type is int.

Step 2 − Return log2(n & -n)+1.

## Example

package main
import (
"fmt"
"math"
"strconv"
)
func FindRightMostSetBit(n int) int {
if (n & 1) != 0{
return 1
}
return int(math.Log2(float64(n & -n))) + 1
}
func main(){
var n = 20
fmt.Printf("Binary of %d is: %s.\n", n, strconv.FormatInt(int64(n), 2))
fmt.Printf("Position of the rightmost set bit of the given number %d is %d.\n", n, FindRightMostSetBit(n))
}

## Output

Binary of 20 is: 10100.
Position of the rightmost set bit of the given number 20 is 3.
Updated on 17-Mar-2021 11:11:57