Skip to content

Conversation

@AliAlimohammadi
Copy link
Contributor

@AliAlimohammadi AliAlimohammadi commented Dec 18, 2025

Description

Adds rightmost_set_bit function that finds the 1-based position of the rightmost (least significant) set bit in a positive integer.

Algorithm

Uses n & -n to isolate the rightmost set bit, then trailing_zeros() + 1 for position.

Example: For n = 18 (binary: 10010):

  • n & -n = 2 (binary: 10)
  • trailing_zeros(2) = 1
  • position = 1 + 1 = 2

Features

  • $O(1)$ time/space complexity
  • ✅ Hardware-optimized (uses BSF/CTZ instruction)
  • ✅ Two implementations (trailing_zeros and log2)
  • ✅ Comprehensive error handling
  • ✅ 15+ test cases

Examples

rightmost_set_bit(18) // Ok(2)  - binary: 10010
rightmost_set_bit(12) // Ok(3)  - binary: 1100
rightmost_set_bit(5)  // Ok(1)  - binary: 101
rightmost_set_bit(0)  // Err    - no set bits

Testing

All tests pass including:

  • Powers of two
  • Odd numbers (always position 1)
  • Even numbers
  • Edge cases (zero, negatives)
  • Large numbers
  • Both implementations match

Checklist

  • Follows Rust style guidelines
  • Passes clippy lints
  • All tests pass
  • Documentation with examples
  • Properly exported

@AliAlimohammadi
Copy link
Contributor Author

@siriak, this is ready to be merged.

@codecov-commenter
Copy link

Codecov Report

❌ Patch coverage is 98.66667% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 95.72%. Comparing base (7a261d7) to head (4798d6c).

Files with missing lines Patch % Lines
src/bit_manipulation/rightmost_set_bit.rs 98.66% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##           master     #975   +/-   ##
=======================================
  Coverage   95.71%   95.72%           
=======================================
  Files         346      347    +1     
  Lines       22608    22683   +75     
=======================================
+ Hits        21639    21713   +74     
- Misses        969      970    +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.

@siriak siriak merged commit 1b3d80d into TheAlgorithms:master Dec 18, 2025
7 checks passed
@AliAlimohammadi AliAlimohammadi deleted the add-rightmost-set-bit branch December 18, 2025 21:17
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