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
}
}
}
`
CodePudding user response:
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
CodePudding user response:
I would use the following solution ( check in the playground )
a number power of 2 means that it is of the following format : 1000..
1 and followed by zeros example:
2 -> 10
4 -> 100
8 -> 1000
16 -> 10000
....
so the idea is to convert the number to binary and check the format if it matches then it is of power 2.
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
fmt.Println(checkPowerTwo(2))
fmt.Println(checkPowerTwo(4))
fmt.Println(checkPowerTwo(8))
fmt.Println(checkPowerTwo(12))
}
func checkPowerTwo(n int64) bool {
// convert to binary
b := strconv.FormatInt(n, 2)
// build the zeros string to check for format
zero := strings.Repeat("0", len(b)-1)
// b[1:] means we excloud the first "1" and we keep the rest
if b[1:] == zero { // if the rest equals "00000..."
return true // then that's of power 2
}
return false // else its not of power 2
}