Golang 程序检查给定的正数是否为 2 的幂,无需使用任何分支或循环

go programmingserver side programmingprogramming更新于 2025/5/10 11:07:17

示例

考虑 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.

相关文章