例如,n = 12 =>以前的2的幂为8。
例如,n = 20 =>以前的2的幂为16。
解决这个问题的方法
步骤1-定义一个接受数字n的方法。
步骤2-执行n | (n >> k),其中k为1、2、4、8、16。
步骤3-最后,返回n-(n >> 1)。
package main import "fmt" func PreviousPowOf2(n int) int{ n = n | (n >> 1) n = n | (n >> 2) n = n | (n >> 4) n = n | (n >> 8) n = n | (n >> 16) return n - (n >> 1) } func main(){ fmt.Printf("Previous round number, power of 2 for %d is %d\n", 20, PreviousPowOf2(20)) fmt.Printf("Previous round number, power of 2 for %d is %d\n", 12, PreviousPowOf2(12)) fmt.Printf("Previous round number, power of 2 for %d is %d\n", 131, PreviousPowOf2(131)) }输出结果
Previous round number, power of 2 for 20 is 16 Previous round number, power of 2 for 12 is 8 Previous round number, power of 2 for 131 is 128