is power of 2 with golang

Viewed 736

I want to check whether the number given is a power of 2. I have written a code but I cannot return true or false, I think somewhere there is an infinite loop. I am only allowed to use functions from imported packages on the code. I could not figure out what to do to correct the mistake. I would be glad if you can help me :)

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
        }
    }
}
`
1 Answers

As commented by @phuclv , I have created a sample program for your scenario by using n & (n - 1) == 0 as follows :

//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)
    }
}

You can run it here : https://go.dev/play/p/9cRWwiFAIn8

Related