MCPcopy Create free account
hub / github.com/TheAlgorithms/Go / IsPowerOfTwo

Function IsPowerOfTwo

math/binary/checkisnumberpoweroftwo.go:23–25  ·  view source on GitHub ↗

IsPowerOfTwo This function uses the fact that powers of 2 are represented like 10...0 in binary, and numbers one less than the power of 2 are represented like 11...1. Therefore, using the and function: 10...0 & 01...1 00...0 -> 0 This is also true for 0, which is not a power of 2, for which

(x int)

Source from the content-addressed store, hash-verified

21// This is also true for 0, which is not a power of 2, for which we
22// have to add and extra condition.
23func IsPowerOfTwo(x int) bool {
24 return x > 0 && (x&(x-1)) == 0
25}
26
27// IsPowerOfTwoLeftShift This function takes advantage of the fact that left shifting a number
28// by 1 is equivalent to multiplying by 2. For example, binary 00000001 when shifted by 3 becomes 00001000,

Callers 2

TestIsPowerOfTwoFunction · 0.85

Calls

no outgoing calls

Tested by 2

TestIsPowerOfTwoFunction · 0.68