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.

更新於:17-Mar-2021

259 瀏覽

開啟你的 職業之路

完成課程獲得認證

入門
廣告
© . All rights reserved.