Last active
August 16, 2024 07:39
-
-
Save nojima/0b99df0b0ce66187e0cd5cb22318cfc5 to your computer and use it in GitHub Desktop.
Efficient way to calculate the minimum power of 2 that is greater than or equal to the given integer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math/bits" | |
) | |
// BitCeil returns the minimum power of 2 that is greater than or equal to x. | |
// It returns 1 when x is 0. | |
func BitCeil(x uint) uint { | |
if x < 2 { | |
return 1 | |
} | |
return 1 << (bits.UintSize - bits.LeadingZeros(x-1)) | |
} | |
func main() { | |
for i := range 30 { | |
fmt.Printf("i = %d, BitCeil(i) = %d\n", i, BitCeil(uint(i))) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment