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.