Golang程序检查给定的正数是否为2的幂,是否不使用任何分支或循环
例子
考虑n=16(00010000)
现在找到x=n-1=>15(00001111)=>x&n=>0
解决这个问题的方法
步骤1-定义一个方法,其中n和是一个参数,返回类型为int。
步骤2-执行x=n&n-1。
步骤3-如果x为0,则给定数字为2的幂;否则,x为0。否则没有。
示例
package main
import (
"fmt"
"strconv"
)
func CheckNumberPowerOfTwo(n int) int {
return n & (n-1)
}
func main(){
var n = 16
fmt.Printf("Binary of %d is: %s.\n", n, strconv.FormatInt(int64(n), 2))
flag := CheckNumberPowerOfTwo(n)
if flag == 0{
fmt.Printf("Given %d number is the power of 2.\n", n)
} else {
fmt.Printf("Given %d number is not the power of 2.\n", n)
}
}输出结果Binary of 16 is: 10000. Given 16 number is the power of 2.
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下