<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:ital,wght@0,300;0,400;0,500;0,600;0,700;1,300;1,400;1,500;1,600;1,700&family=DM+Mono:ital,wght@0,300;0,400;0,500;1,300;1,400;1,500&display=swap" rel="stylesheet"/>

Power of Two in Dart — Bit Trick & Division

By Mihir Pipermitwala · 2 min read

⚡ 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:

Copy
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.

Copy
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.

Copy
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!

Mihir Pipermitwala

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 →
Scroll down to load comments...
Related Blogs
Go JSON v2: A Practical Migration Guide to encoding/json/v2

Go JSON v2: A Practical Migration Guide to encoding/json/v2

Migrate a Go REST API to encoding/json/v2 in 7 steps: struct tags, omitempty, unknown fields, error handling, and jsontext streaming, plus a v1 vs v2 comparison.

GOTUTORIALDEVELOPER TOOLS

November 12, 2026

Unlocking Flutter's Potential: Best Practices for Writing Clean Code

Unlocking Flutter's Potential: Best Practices for Writing Clean Code

Unlock Flutter's potential with clean code. Learn best practices for writing maintainable Dart code, with examples and essential principles.

CLEAN CODECODE BEST PRACTICESCODE MAINTAINABILITYCODE ORGANIZATIONCODE READABILITY

June 02, 2023

Top 9 Local Databases for Flutter: Full Comparison

Top 9 Local Databases for Flutter: Full Comparison

Compare the best local databases for Flutter (Isar, Hive, Sqflite, ObjectBox, Realm, Drift, Floor, CBL, Sembast). Find pros, cons, and performance comparisons.

CODINGFLUTTERFLUTTER LOCAL DATABASESLEARN TO CODENOSQL

April 06, 2023

Related Tutorials
Essential Git Skills: How to Delete Remote Branches

Essential Git Skills: How to Delete Remote Branches

Keep your repository clean and organized. This guide walks you through how to delete both local and remote branches in Git, step by step.

BITBUCKETDELETE LOCAL BRANCHDELETE REMOTE BRANCHGITGIT BRANCH CLEANUP AUTOMATION

June 12, 2024

Show an Offline Message for No Internet in Flutter

Show an Offline Message for No Internet in Flutter

You have to use the 'Connectivity Flutter Package' to achieve this feature on your App. This package helps to know whether your device is online or offline.

CONNECTIVITY PLUSDEPENDENCIESFLUTTERFLUTTER DEVELOPMENTFLUTTER PACKAGES

April 09, 2024

Mastering TabBar & TabBarView in Flutter: A Complete Guide

Mastering TabBar & TabBarView in Flutter: A Complete Guide

Implement TabBar and TabBarView in Flutter step by step — customize tab indicators, enable scrollable tabs, and change tabs programmatically.

CODINGDEFAULT TAB CONTROLLERFLUTTERLEARN TO CODETAB CONTROLLER

July 26, 2023

File Manipulation in Flutter: Best Practices & Examples

File Manipulation in Flutter: Best Practices & Examples

Master Flutter file manipulation — permission management, directory handling, and practical read-write scenarios to elevate your app's file handling.

CODINGFLUTTERFLUTTER DEVELOPMENTFLUTTER FILE OPERATIONFLUTTER PATH PROVIDER

June 30, 2023

Related Problems
Power of Two in Python — Bit Trick & Division

Power of Two in Python — Bit Trick & Division

Check power of two in Python with working code. Bit manipulation approach with O(1) time, plus complexity analysis and interview tips.

PYTHONPROGRAMMING PATTERNSLEARN TO CODETUTORIAL

November 28, 2026

Power of Two in Go — Bit Trick & Division

Power of Two in Go — Bit Trick & Division

Check power of two in Go with working code. Bit manipulation approach with O(1) time, plus complexity analysis and interview tips.

GOLANGPROGRAMMING PATTERNSLEARN TO CODETUTORIAL

November 28, 2026

Power of Two in Swift — Bit Trick & Division

Power of Two in Swift — Bit Trick & Division

Check power of two in Swift with working code. Bit manipulation approach with O(1) time, plus complexity analysis and interview tips.

SWIFTPROGRAMMING PATTERNSLEARN TO CODETUTORIAL

November 28, 2026

Missing Number in Dart — Sum Formula & XOR

Missing Number in Dart — Sum Formula & XOR

Solve Missing Number in Dart with working code. Sum formula approach with O(n) time, plus complexity analysis and interview tips.

DART PROGRAMMINGPROGRAMMING PATTERNSLEARN TO CODETUTORIAL

November 25, 2026

Count Primes in Dart — Sieve of Eratosthenes

Count Primes in Dart — Sieve of Eratosthenes

Count primes below n in Dart with working code. Sieve of Eratosthenes approach with O(n log log n) time, plus complexity analysis and interview tips.

DART PROGRAMMINGPROGRAMMING PATTERNSLEARN TO CODETUTORIAL

November 26, 2026

Related Recommended Services
Visual Studio Code for the Web

Visual Studio Code for the Web

Build with Visual Studio Code, anywhere, anytime, in your browser.

IDEVISUAL STUDIOVISUAL STUDIO CODEWEB
Renovate | Automated Dependency Updates

Renovate | Automated Dependency Updates

Renovate Bot keeps source code dependencies up-to-date using automated Pull Requests.

AUTOMATED DEPENDENCY UPDATESBUNDLERCOMPOSERGITHUBGO MODULES
Best XML Formatter and XML Beautifier

Best XML Formatter and XML Beautifier

Online XML Formatter will format xml data, helps to validate, and works as XML Converter. Save and Share XML.

XMLXML BEAUTIFIERXML CONVERTERXML FORMATXML FORMATTER
Kubecost | Kubernetes cost monitoring and management

Kubecost | Kubernetes cost monitoring and management

Kubecost started in early 2019 as an open-source tool to give developers visibility into Kubernetes spend. We maintain a deep commitment to building and supporting dedicated solutions for the open source community.

CLOUDKUBECOSTKUBERNETESOPEN SOURCESELF HOSTED
Related Recommended Stories
How GitHub reduced testing time for iOS apps with new runner features

How GitHub reduced testing time for iOS apps with new runner features

Learn how GitHub used macOS and Apple Silicon runners for GitHub Actions to build, test, and deploy our iOS app faster.

IOSGITHUBTESTINGRUNNER
5 ways to transform your workflow using GitHub Copilot and MCP

5 ways to transform your workflow using GitHub Copilot and MCP

Learn how to streamline your development workflow with five different MCP use cases.

AGENT MODECODING AGENTCOPILOTFIGMAGITHUB
One weird trick for powerful Git aliases

One weird trick for powerful Git aliases

Advanced Git Aliases

ALIASALIAS TEMPLATEATLASSIANBITBUCKETGIT
Awesome Python

Awesome Python

An opinionated list of awesome Python frameworks, libraries, software and resources

AWESOMEAWESOME PYTHONCOLLECTIONSGITHUBPYTHON
Related Recommended Tools
Find out what websites are built with - Wappalyzer

Find out what websites are built with - Wappalyzer

Find out the technology stack of any website. Create lists of websites and contacts by the technologies they use.

ADD ONSANALYTICSAPP STOREAPPLEBOOKING
Sourcetree | Free Git GUI for Mac and Windows

Sourcetree | Free Git GUI for Mac and Windows

A Git GUI that offers a visual representation of your repositories. Sourcetree is a free Git client for Windows and Mac.

GITGITHUBGITLABATLASSIANBITBUCKET
Related Recommended Videos