Golang Program to check whether given positive number is power of 2 or not, without using any branching or loop

Go ProgrammingServer Side ProgrammingProgramming

Examples

Consider n = 16(00010000)

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

Approach to solve this problem

Step 1 − Define a method, where n and is an argument, returns type is int.

Step 2 − Perform x = n & n-1.

Step 3 − If x is 0, then the given number is power of 2; else not.

Example

Live Demo

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

Output

Binary of 16 is: 10000.
Given 16 number is the power of 2.
Published on 17-Mar-2021 11:02:35