Golang程序 检查给定的正数是否为2的幂

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的幂;否则不是。

例子

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.

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程