Go 语言程序,检查给定的正数是否为 2 的幂,不使用任何分支或循环
示例
设 n = 16(00010000)
现在求 x = n-1 => 15(00001111) => x & n => 0
解决此问题的方法
步骤 1 − 定义方法,其中 n 与参数相同,返回类型为 int。
步骤 2 − 执行 x = n & n-1。
步骤 3 − 如果 x 为 0,则给定的数字为 2 的幂;否则不是。
示例
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.
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP