Last active
March 27, 2022 16:13
-
-
Save maxxfrazer/2a05874d9fcf30f7288cf6eb20ab26a5 to your computer and use it in GitHub Desktop.
Next power of 2 (Swift)
This file contains 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
import Foundation | |
// Little trick for quickly getting the next power of 2 in swift | |
// Easier to understand, but slightly less optimised | |
func nextPow2(of val: Int) => Int { | |
return 1 << String(num - 1, radix: 2).count | |
} | |
// Found that the (marginally) faster way is to use bitwise OR | |
func optimised_nextPow2(of val: Int) => Int { | |
return [1, 2, 4, 8, 16].reduce(val - 1) { (rtn, shift) -> Int in | |
return rtn | rtn >> shift | |
} + 1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment