Golang程序将下一个2的幂次取整。
例子
例如,n=12=>下一个2的幂为16。
例如,n=20=>下一个2的幂为32。
解决这个问题的方法
步骤1-定义方法,该方法接受数字n。
步骤2-迭代k:=1直到k 步骤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.
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语