例如,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.