// "11" "1" "100"
// "1010" "1011" "10101"
// 位运算
pub fn add_binary(a: String, b: String) -> String {
let mut result = String::new();
let mut carry = 0;
let a_bytes = a.as_bytes();
let b_bytes = b.as_bytes();
let mut i = a.len() as i32 - 1;
let mut j = b.len() as i32 - 1;
while i >= 0 || j >= 0 || carry > 0 {
let mut sum = carry;
if i >= 0 {
sum += (a_bytes[i as usize] - b'0') as i32;
i -= 1;
}
if j >= 0 {
sum += (b_bytes[j as usize] - b'0') as i32;
j -= 1;
}
carry = sum / 2;
result.push(((sum % 2) as u8 + b'0') as char);
}
result.chars().rev().collect()
}
// 模拟
pub fn add_binary2(a: String, b: String) -> String {
let mut a = a.chars().rev().collect::<Vec<char>>();
let mut b = b.chars().rev().collect::<Vec<char>>();
let mut result = Vec::new();
let mut carry = 0;
let n = a.len().max(b.len());
for i in 0..n {
let digit_a = if i < a.len() { a[i].to_digit(10).unwrap() } else { 0 };
let digit_b = if i < b.len() { b[i].to_digit(10).unwrap() } else { 0 };
let sum = digit_a + digit_b + carry;
carry = sum / 2;
result.push((sum % 2).to_string());
}
if carry > 0 {
result.push(carry.to_string());
}
result.reverse();
result.join("")
}
fn main() {
assert_eq!(add_binary("10".to_string(), "1".to_string()), "11");
assert_eq!(add_binary("1010".to_string(), "1011".to_string()), "10101");
assert_eq!(add_binary2("10".to_string(), "1".to_string()), "11");
assert_eq!(add_binary2("1010".to_string(), "1011".to_string()), "10101");
}
leetcode简单题13 N.67 二进制求和 rust描述
最新推荐文章于 2024-10-15 19:28:18 发布