Skip to content

Conversation

@AliAlimohammadi
Copy link
Contributor

@AliAlimohammadi AliAlimohammadi commented Dec 17, 2025

Description

Adds an algorithm to count trailing zeros in the binary representation of a number.

Algorithm

Counts the number of consecutive zeros from the least significant bit (rightmost) in the binary representation of an unsigned integer.

Time Complexity: O(1) - uses CPU instruction
Space Complexity: O(1)

Example

assert_eq!(binary_count_trailing_zeros(25), 0);   // 11001 -> 0 trailing zeros
assert_eq!(binary_count_trailing_zeros(36), 2);   // 100100 -> 2 trailing zeros
assert_eq!(binary_count_trailing_zeros(16), 4);   // 10000 -> 4 trailing zeros
assert_eq!(binary_count_trailing_zeros(58), 1);   // 111010 -> 1 trailing zero

Implementation Details

  • Primary: Uses Rust's built-in trailing_zeros() method
  • Alternative: Bitwise implementation using log2(num & -num) trick
  • Compiles to single CPU instruction (BSF/TZCNT on x86)
  • Handles zero case explicitly to return 0
  • Type-safe: uses u64 for compile-time guarantees

Testing

  • All existing tests pass
  • Added test suite covering:
    • Basic cases from Python examples
    • Zero handling
    • Powers of 2
    • Comprehensive bitwise vs built-in comparison (22 test cases)

Checklist

  • Code follows the repository's style guidelines
  • Self-review performed
  • Code is well-commented
  • Tests added and passing
  • Documentation added

@codecov-commenter
Copy link

codecov-commenter commented Dec 17, 2025

Codecov Report

❌ Patch coverage is 97.43590% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 95.70%. Comparing base (5c4593c) to head (28d769d).

Files with missing lines Patch % Lines
...rc/bit_manipulation/binary_count_trailing_zeros.rs 97.43% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##           master     #972   +/-   ##
=======================================
  Coverage   95.70%   95.70%           
=======================================
  Files         345      346    +1     
  Lines       22569    22608   +39     
=======================================
+ Hits        21599    21638   +39     
  Misses        970      970           

☔ 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 siriak merged commit 7a261d7 into TheAlgorithms:master Dec 17, 2025
7 checks passed
@AliAlimohammadi AliAlimohammadi deleted the add-binary-trailing-zeros branch December 17, 2025 23:11
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