golang 是 2 的幂

eli*_*lia 5 math go

我想检查给定的数字是否是2的幂。我已经编写了代码,但我无法返回true或false,我认为某个地方存在无限循环。我只允许在代码上使用导入包中的函数。我不知道该怎么做才能纠正这个错误。如果你能帮助我,我会很高兴:)

package main

import (
    "os"
    "strconv"
)

func main() {
    for len(os.Args) == 2 {
        numbers, err := strconv.Atoi(os.Args[1])
        if err != nil {
            panic(err)
        }
        newnum := numbers
        counts := 0
        for numbers != 1 {
            if newnum%2 != 0 {
            } else {
                newnum = newnum / 2
            }
            counts++
        }
        var x int = 2 ^ counts
        if x == numbers {
            return true
        } else {
            return false
        }
    }
}
`
Run Code Online (Sandbox Code Playgroud)

小智 7

正如 @phuclv 所评论的,我使用 n & (n - 1) == 0以下方法为您的场景创建了一个示例程序:

//Let's assume n = 16(00010000)

//Now find x = n-1 => 15(00001111) => x & n => 0

func CheckPowerOfTwo(n int) int {
    //added one corner case if n is zero it will also consider as power 2
    if n==0{
    return 1
    }
    return n & (n - 1)
}
func main() {
    var n = 16
    flag := CheckPowerOfTwo(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)
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以在这里运行它: https: //go.dev/play/p/9cRWwiFAIn8