⚡ TL;DR
Check power of two in Dart 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.
bool isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
void main() {
List<int> values = [1, 16, 18, 0];
for (final v in values) {
print('$v -> ${isPowerOfTwo(v) ? "true" : "false"}');
}
}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.
bool isPowerOfTwoDivide(int n) {
if (n <= 0) {
return false;
}
while (n % 2 == 0) {
n ~/= 2;
}
return n == 1;
}
void main() {
List<int> values = [1, 16, 18, 0];
for (final v in values) {
print('$v -> ${isPowerOfTwoDivide(v) ? "true" : "false"}');
}
}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 Dart?
The recommended approach is Bit Mask Trick, which runs in O(1) time with O(1) space. The full Dart implementation is shown above.
What is the time complexity of Power of Two in Dart?
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 →