Skip to content

Conversation

@AliAlimohammadi
Copy link
Contributor

Description

This PR adds an efficient $O(1)$ implementation to check if a number is a power of two using bit manipulation.

Type of change

  • New algorithm implementation

Changes

  • Added is_power_of_two.rs with comprehensive documentation
  • Includes 13 test functions with 60+ assertions
  • Uses elegant bit manipulation: n & (n - 1) == 0
  • Follows Rust best practices and TheAlgorithms conventions

Algorithm

The implementation uses the property that powers of two have exactly one bit set.
By checking if n & (n - 1) == 0, we can determine in $O(1)$ time if a number is a power of two.

Checklist

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

@codecov-commenter
Copy link

codecov-commenter commented Dec 16, 2025

Codecov Report

❌ Patch coverage is 98.24561% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 95.70%. Comparing base (ebc3767) to head (4573782).

Files with missing lines Patch % Lines
src/bit_manipulation/is_power_of_two.rs 98.24% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #970      +/-   ##
==========================================
+ Coverage   95.68%   95.70%   +0.01%     
==========================================
  Files         343      344       +1     
  Lines       22412    22526     +114     
==========================================
+ Hits        21445    21558     +113     
- Misses        967      968       +1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@AliAlimohammadi
Copy link
Contributor Author

@siriak, this is ready to be merged.

@siriak
Copy link
Member

siriak commented Dec 16, 2025

How is this different from #969?

@AliAlimohammadi
Copy link
Contributor Author

AliAlimohammadi commented Dec 16, 2025 via email

@siriak siriak merged commit 98400e1 into TheAlgorithms:master Dec 16, 2025
7 checks passed
@AliAlimohammadi AliAlimohammadi deleted the add-is-power-of-two branch December 16, 2025 20:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants