Golang 程式用於向上取整到下一個最高 2 次冪。


示例

例如,n = 12 => 下一個 2 次冪為 16。

例如,n = 20 => 下一個 2 次冪為 32。

解決這個問題的方法

步驟 1 − 定義接受數字 n 的方法。

步驟 2 − 迭代 k := 1 直到 k < n。

步驟 3 − 在迴圈中,計算 k << 1。

步驟 4 − 最後,返回 k。

示例

 演示

package main
import "fmt"
func NextPowOf2(n int) int{
   k := 1
   for ;k < n; {
      k = k << 1
   }
   return k
}
func main(){
   fmt.Printf("Round of highest power of 2 for %d is %d.\n", 20, NextPowOf2(20))
   fmt.Printf("Round of highest power of 2 for %d is %d.\n", 16, NextPowOf2(16))
   fmt.Printf("Round of highest power of 2 for %d is %d.\n", 131, NextPowOf2(131))
}

輸出

Round of highest power of 2 for 20 is 32.
Round of highest power of 2 for 16 is 16.
Round of highest power of 2 for 131 is 256.

更新於: 18-Mar-2021

已檢視 472 次

啟動您的事業

完成課程以獲得認證

開始
廣告
© . All rights reserved.