Golang 程式尋找最右邊設定位的位置
示例
假設 n = 20(00010100)
現在返回 log2(20 & -20) => 2 + 1 => 3
解決此問題的方法
步驟 1 - 定義一個方法,其中 n 和是引數,返回型別為 int。
步驟 2 - 返回 log2(n & -n)+ 1。
示例
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))
}輸出
Binary of 20 is: 10100. Position of the rightmost set bit of the given number 20 is 3.
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP