⚡ TL;DR
Check power of two in Go with working code. Bit manipulation approach with O(1) time, plus complexity analysis and interview tips.
Power of Two (#231 — Easy): Given an integer n, return true if it is a power of two. Otherwise, return false.
Problem Statement
Given an integer n, return true if it is a power of two. Otherwise, return false.
Example:
Input: n = 16
Output: true
Explanation: 16 = 2⁴, so it is a power of two.Approach: Bit Mask Trick
Time: O(1) | Space: O(1)
A power of two has exactly one set bit: 1, 10, 100, 1000… Subtracting 1 flips that bit and sets every bit below it, so n & (n−1) is zero only for powers of two — guarded by n > 0.
package main
import "fmt"
func isPowerOfTwo(n int) bool {
return n > 0 && n&(n-1) == 0
}
func main() {
for _, v := range []int{1, 16, 18, 0} {
label := "false"
if isPowerOfTwo(v) {
label = "true"
}
fmt.Println(v, "->", label)
}
}Approach: Repeated Division
Time: O(log n) | Space: O(1)
Divide by 2 while the value is even; a true power of two collapses all the way to 1. Simple to reason about and a good baseline before reaching for the bit trick.
package main
import "fmt"
func isPowerOfTwoDivide(n int) bool {
if n <= 0 {
return false
}
for n%2 == 0 {
n /= 2
}
return n == 1
}
func main() {
for _, v := range []int{1, 16, 18, 0} {
label := "false"
if isPowerOfTwoDivide(v) {
label = "true"
}
fmt.Println(v, "->", label)
}
}Key Takeaways
- n & (n−1) == 0 is the one-line signature of a power of two
- The n > 0 guard matters: 0 and negatives pass the bit check but are not powers of two
- Repeated division is the readable fallback when bit tricks feel opaque
FAQ
What is the best approach to solve Power of Two in Go?
The recommended approach is Bit Mask Trick, which runs in O(1) time with O(1) space. The full Go implementation is shown above.
What is the time complexity of Power of Two in Go?
Using Bit Mask Trick, the time complexity is O(1) and the space complexity is O(1); Repeated Division runs in O(log n) time with O(1) space.
Happy coding!

Written by Mihir Pipermitwala
Senior Full Stack Consultant & Mobile Engineering Specialist building user-focused applications in healthcare with Flutter, Dart and React Native. I write about what I actually build and test — every tutorial here comes from real project work.
More about Mihir →