Skip to content

Conversation

@AliAlimohammadi
Copy link
Contributor

Description

Adds the Binary Coded Decimal (BCD) algorithm to the bit manipulation module.

This algorithm converts a decimal integer to Binary Coded Decimal format, where each decimal digit is represented by its 4-bit binary equivalent.

Implementation Details

  • Converts each decimal digit (0-9) to a 4-bit binary representation
  • Uses fold with write! macro for efficient string building
  • Handles negative numbers by treating them as 0 (matching Python implementation)
  • Returns result with "0b" prefix for consistency
  • Time Complexity: O(n) where n is the number of digits
  • Space Complexity: O(n) for the output string

Examples

binary_coded_decimal(12)   // Returns "0b00010010" (1=0001, 2=0010)
binary_coded_decimal(987)  // Returns "0b100110000111" (9=1001, 8=1000, 7=0111)
binary_coded_decimal(-5)   // Returns "0b0000" (negative → 0)

Testing

  • Added comprehensive unit tests covering:
    • Zero and single digits (0-9)
    • Two-digit numbers
    • Three-digit numbers
    • Large numbers (4+ digits)
    • Negative numbers
    • Specific digit encoding verification
  • All tests pass with cargo test
  • Doctests pass with correct import paths
  • Code formatted with cargo fmt
  • No clippy warnings (uses fold and write! for efficiency)

Checklist

  • I have tested the code
  • I have run cargo fmt
  • I have run cargo clippy
  • I have added documentation
  • I have added tests

@codecov-commenter
Copy link

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.63%. Comparing base (e877687) to head (b1ba689).

Additional details and impacted files
@@           Coverage Diff           @@
##           master     #966   +/-   ##
=======================================
  Coverage   95.62%   95.63%           
=======================================
  Files         339      340    +1     
  Lines       22078    22127   +49     
=======================================
+ Hits        21113    21161   +48     
- Misses        965      966    +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 siriak merged commit 69100c0 into TheAlgorithms:master Dec 13, 2025
7 checks passed
@AliAlimohammadi AliAlimohammadi deleted the add-binary-coded-decimal branch December 13, 2025 23:00
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