How to write 4 different functions that check if a number is a power of 2 in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "math"
)

// Method A: Bit‑counting
func isPowerOfTwoA(x int) bool {
    if x <= 0 {
        return false
    }
    count := 0
    for x > 0 {
        if x&1 == 1 {
            count++
        }
        x >>= 1
    }
    return count == 1
}

// Method B: Bitwise trick
func isPowerOfTwoB(x int) bool {
    return x > 0 && (x&(x-1)) == 0
}

// Method C: Repeated division
func isPowerOfTwoC(x int) bool {
    if x <= 0 {
        return false
    }
    for x%2 == 0 {
        x /= 2
    }
    return x == 1
}

// Method D: Using logarithms
func isPowerOfTwoD(x int) bool {
    if x <= 0 {
        return false
    }
    logv := math.Log2(float64(x))
    return math.Abs(logv-math.Round(logv)) < 1e-10
}

func main() {
    test1 := 16 // true
    test2 := 18 // false

    fmt.Println("A:", isPowerOfTwoA(test1), ",", isPowerOfTwoA(test2))
    fmt.Println("B:", isPowerOfTwoB(test1), ",", isPowerOfTwoB(test2))
    fmt.Println("C:", isPowerOfTwoC(test1), ",", isPowerOfTwoC(test2))
    fmt.Println("D:", isPowerOfTwoD(test1), ",", isPowerOfTwoD(test2))
}


/*
OUTPUT:

A: true , false
B: true , false
C: true , false
D: true , false

*/

 



answered Apr 2 by avibootz

Related questions

...