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.

更新於: 2021-03-17

584 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.