-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadd_binary.rs
97 lines (84 loc) · 2.53 KB
/
add_binary.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#![allow(dead_code)]
pub fn add_binary(a: String, b: String) -> String {
let mut a = a.chars().rev();
let mut b = b.chars().rev();
let mut carry = 0;
let mut result = String::new();
loop {
match (a.next(), b.next()) {
(None, None) => {
if carry == 1 {
result.push('1');
}
break;
}
(Some(a), None) => {
let sum = a.to_digit(10).unwrap() + carry;
if sum == 2 {
result.push('0');
carry = 1;
} else {
result.push_str(&sum.to_string());
carry = 0;
}
}
(None, Some(b)) => {
let sum = b.to_digit(10).unwrap() + carry;
if sum == 2 {
result.push('0');
carry = 1;
} else {
result.push_str(&sum.to_string());
carry = 0;
}
}
(Some(a), Some(b)) => {
let sum = a.to_digit(10).unwrap() + b.to_digit(10).unwrap() + carry;
if sum == 2 {
result.push('0');
carry = 1;
} else if sum == 3 {
result.push('1');
carry = 1;
} else {
result.push_str(&sum.to_string());
carry = 0;
}
}
}
}
result.chars().rev().collect()
}
/*
Algorithm:
- Convert the strings to chars and reverse them
- Loop through the chars and add them together
- If the sum is 2, add 0 to the result and carry 1
- If the sum is 3, add 1 to the result and carry 1
- If the sum is 1, add 1 to the result and carry 0
- If the sum is 0, add 0 to the result and carry 0
- If there is a carry at the end, add 1 to the result
- Reverse the result and return it
Time complexity:
- O(n) where n is the length of the longest string
Space complexity:
- O(n) where n is the length of the longest string
*/
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1() {
assert_eq!(
add_binary("11".to_string(), "1".to_string()),
"100".to_string()
);
}
#[test]
fn test_2() {
assert_eq!(
add_binary("1010".to_string(), "1011".to_string()),
"10101".to_string()
);
}
}