-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths0067_add_binary.rs
More file actions
107 lines (87 loc) · 2.2 KB
/
s0067_add_binary.rs
File metadata and controls
107 lines (87 loc) · 2.2 KB
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
98
99
100
101
102
103
104
105
106
107
#![allow(unused)]
pub struct Solution {}
use std::cmp::max;
impl Solution {
//Time O(N) Space O(N)
pub fn add_binary(a: String, b: String) -> String {
let (m, n) = (a.len(), b.len());
if m < n {
return Self::add_binary(b, a);
}
let len = max(m, n);
let mut carry = 0;
let mut j = (n - 1) as i32;
let b_str = b.as_str();
let mut ans = "".to_string();
for c in a.chars().rev() {
if c == '1' {
carry += 1;
}
if j >= 0 && &b_str[j as usize..(j+1) as usize] == "1" {
carry += 1;
}
j -= 1;
if carry % 2 == 1 {
ans.push('1');
} else {
ans.push('0');
}
carry /= 2;
}
if carry == 1 {
ans.push('1');
}
// reverse a string
ans.chars().rev().collect()
}
pub fn add_binary_repeat(a: String, b: String) -> String {
let (m, n) = (a.len(), b.len());
if m < n {
return Self::add_binary(b, a);
}
let mut carry = 0;
let mut ans = "".to_string();
// chain(std::iter::repeat('0') mean shorter will put 000...0 ulimited
for (ac, bc) in a.chars().rev().zip(b.chars().rev().chain(std::iter::repeat('0'))) {
if ac == '1' {
carry += 1;
}
if bc == '1' {
carry += 1;
}
if carry % 2 == 1 {
ans.push('1');
} else {
ans.push('0');
}
carry /= 2;
}
if carry == 1 {
ans.push('1');
}
ans.chars().rev().collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_67() {
assert_eq!(
Solution::add_binary_repeat("11".to_string(), "1".to_string()),
"100".to_string()
);
assert_eq!(
Solution::add_binary_repeat("1010".to_string(), "1011".to_string()),
"10101".to_string()
);
assert_eq!(
Solution::add_binary("11".to_string(), "1".to_string()),
"100".to_string()
);
assert_eq!(
Solution::add_binary("1010".to_string(), "1011".to_string()),
"10101".to_string()
);
}
}