leetcode简单题13 N.67 二进制求和 rust描述

// "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");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值