Skip to content

Commit 963f29f

Browse files
authored
Add decimal to binary conversion (TheAlgorithms#465)
1 parent 86a85b6 commit 963f29f

File tree

3 files changed

+30
-0
lines changed

3 files changed

+30
-0
lines changed

src/conversions/decimal_to_binary.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
pub fn decimal_to_binary(base_num: u64) -> String {
2+
let mut num = base_num;
3+
let mut binary_num = String::new();
4+
loop {
5+
let bit = (num % 2).to_string();
6+
binary_num.push_str(&bit);
7+
num /= 2;
8+
if num == 0 {
9+
break;
10+
}
11+
}
12+
13+
let bits = binary_num.chars();
14+
bits.rev().collect()
15+
}
16+
17+
#[cfg(test)]
18+
mod tests {
19+
use super::*;
20+
21+
#[test]
22+
fn converting_decimal_to_binary() {
23+
assert_eq!(decimal_to_binary(542), "1000011110");
24+
assert_eq!(decimal_to_binary(92), "1011100");
25+
}
26+
}

src/conversions/mod.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
mod decimal_to_binary;
2+
3+
pub use self::decimal_to_binary::decimal_to_binary;

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ pub mod backtracking;
44
pub mod big_integer;
55
pub mod ciphers;
66
pub mod compression;
7+
pub mod conversions;
78
pub mod data_structures;
89
pub mod dynamic_programming;
910
pub mod general;

0 commit comments

Comments
 (0)