|
| 1 | +/* |
| 2 | + * Problem: 67. Add Binary (Easy) |
| 3 | + * URL: https://leetcode.com/problems/add-binary/ |
| 4 | + * |
| 5 | + * Runtime: 1 ms (66.20%) |
| 6 | + * Memory Usage: 2.02 MB (71.83%) |
| 7 | + */ |
| 8 | + |
| 9 | +pub fn solve(a: String, b: String) -> String { |
| 10 | + let short: String; |
| 11 | + let long = if b.len() > a.len() { |
| 12 | + short = a; |
| 13 | + b |
| 14 | + } else { |
| 15 | + short = b; |
| 16 | + a |
| 17 | + }; |
| 18 | + |
| 19 | + let mut result = "0".repeat(long.len()+1); |
| 20 | + |
| 21 | + let mut i = 0; |
| 22 | + let mut carryover = false; |
| 23 | + |
| 24 | + let mut i_long: &str; |
| 25 | + let mut i_short: &str; |
| 26 | + let mut oper_range; |
| 27 | + |
| 28 | + // Step 1: Add short string into long string |
| 29 | + while(i < short.len()) { |
| 30 | + i_long = &long[long.len()-i-1..long.len()-i]; |
| 31 | + i_short = &short[short.len()-i-1..short.len()-i]; |
| 32 | + |
| 33 | + oper_range = long.len()-i..long.len()-i+1; |
| 34 | + |
| 35 | + if(carryover) { |
| 36 | + if(i_long == "0" && i_short == "0") { |
| 37 | + result.replace_range(oper_range, "1"); |
| 38 | + carryover = false; |
| 39 | + } |
| 40 | + else if (i_long == "1" && i_short == "1") { |
| 41 | + result.replace_range(oper_range, "1"); |
| 42 | + } |
| 43 | + } else { |
| 44 | + if(i_long == "0" && i_short == "0") {} |
| 45 | + else if (i_long == "1" && i_short == "1") { carryover = true; } |
| 46 | + else { result.replace_range(oper_range, "1") } |
| 47 | + } |
| 48 | + |
| 49 | + i += 1; |
| 50 | + |
| 51 | + // println!("{}: {}", i, result); |
| 52 | + } |
| 53 | + |
| 54 | + // Step 2: Complete addition of long string with carryover |
| 55 | + while i < long.len() { |
| 56 | + i_long = &long[long.len()-i-1..long.len()-i]; |
| 57 | + oper_range = long.len()-i..long.len()-i+1; |
| 58 | + |
| 59 | + if(carryover) { |
| 60 | + if i_long == "0" { |
| 61 | + carryover = false; |
| 62 | + result.replace_range(oper_range, "1"); |
| 63 | + } |
| 64 | + } else { |
| 65 | + if i_long== "1" { result.replace_range(oper_range, "1") } |
| 66 | + } |
| 67 | + |
| 68 | + i += 1; |
| 69 | + } |
| 70 | + |
| 71 | + // Step 3: Add "1" if remaining carryover |
| 72 | + if carryover { result.replace_range(0..1, "1") } |
| 73 | + |
| 74 | + return if &result[0..1] == "1" { result } else { result[1..result.len()].to_string()}; |
| 75 | +} |
| 76 | + |
| 77 | +#[cfg(test)] |
| 78 | +mod add_binary_tests { |
| 79 | + use super::*; |
| 80 | + |
| 81 | + #[test] |
| 82 | + fn equal_length() { |
| 83 | + let a = String::from("1010"); |
| 84 | + let b = String::from("1011"); |
| 85 | + |
| 86 | + assert_eq!(solve(a, b), "10101"); |
| 87 | + } |
| 88 | + |
| 89 | + #[test] |
| 90 | + fn different_lengths() { |
| 91 | + let a = String::from("100"); |
| 92 | + let b = String::from("10001"); |
| 93 | + |
| 94 | + assert_eq!(solve(a, b), "10101"); |
| 95 | + } |
| 96 | +} |
0 commit comments