Skip to content

Commit 926e35e

Browse files
authored
Merge pull request #1641 from AkifhanIlgaz/0067
0067
2 parents f31d911 + a200298 commit 926e35e

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

rust/0067-add-binary.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
impl Solution {
2+
pub fn add_binary(a: String, b: String) -> String {
3+
let mut res = String::new();
4+
let mut carry = 0;
5+
6+
let (mut a, mut b) = (a.as_bytes().to_owned(), b.as_bytes().to_owned());
7+
a.reverse();
8+
b.reverse();
9+
10+
for i in 0..a.len().max(b.len()) {
11+
let digit_a = if i < a.len() { a[i] - b'0' } else { 0 };
12+
let digit_b = if i < b.len() { b[i] - b'0' } else { 0 };
13+
14+
let total = digit_a + digit_b + carry;
15+
let char = (total % 2).to_string();
16+
res = char + &res;
17+
carry = total / 2
18+
}
19+
20+
if carry != 0 {
21+
res = "1".to_string() + &res;
22+
}
23+
res
24+
}
25+
}

0 commit comments

Comments
 (0)