# Golang Program to round up the next previous power of 2.

Go ProgrammingServer Side ProgrammingProgramming

#### Cyber Security : Go from Zero to Hero

Most Popular

60 Lectures 5.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

#### C Programming from scratch- Master C Programming

Best Seller

60 Lectures 8 hours

## Examples

For example, n = 12 => Previous number power of 2 is 8.

For example, n = 20 => Previous number power of 2 is 16.

Approach to solve this problem

Step 1 − Define a method that accepts a number n.

Step 2 − Perform n | (n >> k), where k is 1, 2, 4, 8, 16.

Step 3 − At the end, return n - (n >> 1).

## Example

Live Demo

package main
import "fmt"
func PreviousPowOf2(n int) int{
n = n | (n >> 1)
n = n | (n >> 2)
n = n | (n >> 4)
n = n | (n >> 8)
n = n | (n >> 16)
return n - (n >> 1)
}
func main(){
fmt.Printf("Previous round number, power of 2 for %d is %d\n", 20, PreviousPowOf2(20))
fmt.Printf("Previous round number, power of 2 for %d is %d\n", 12, PreviousPowOf2(12))
fmt.Printf("Previous round number, power of 2 for %d is %d\n", 131, PreviousPowOf2(131))
}

## Output

Previous round number, power of 2 for 20 is 16
Previous round number, power of 2 for 12 is 8
Previous round number, power of 2 for 131 is 128