- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

## 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

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

- Related Questions & Answers
- Golang Program to round up the next highest power of 2.
- Golang Program to check the power of 4 of a given number
- Java Program to get previous and next index using ListIterator
- Program to find Reordered Power of 2 in Python
- Program to find out the value of a power of 2 in Python
- Round number down to nearest power of 10 JavaScript
- Use previous and next class for alignment of links
- How to round up to the nearest N in JavaScript
- C/C++ Program to Find sum of Series with n-th term as n power of 2 - (n-1) power of 2
- Golang Program to check whether given positive number is power of 2 or not, without using any branching or loop
- Reordered Power of 2 in C++
- How to round up a number in JavaScript?
- Nearest power 2 of a number - JavaScript
- C# program to display the previous day
- How to find the previous and next record using a single query in MySQL?

Advertisements