「LeetCode笔记」67.二进制求和-C++与Rust实现

给你两个二进制字符串,返回它们的和(用二进制表示)。

输入为 非空 字符串且只包含数字 1 和 0。

 

示例 1:

输入: a = "11", b = "1"
输出: "100"
示例 2:

输入: a = "1010", b = "1011"
输出: "10101"
 

提示:

每个字符串仅由字符 '0' 或 '1' 组成。
1 <= a.length, b.length <= 10^4
字符串如果不是 "0" ,就都不含前导零。

C++实现

class Solution {
public:
    string addBinary(string a, string b) {
        int cnt = 0;
        int tmpsum = 0;
        int add = 0;
        string res;
        int alen = a.size();
        int blen = b.size();
        for(int ia = alen - 1,ib = blen -1;ia >= 0||ib >= 0;ia--,ib--){
            int ac = (ia >= 0 )?(a[ia]-'0'):0;
            int bc = (ib >= 0 )?(b[ib]-'0'):0;
            tmpsum = ac + bc+ cnt;
            cnt = tmpsum / 2;
            add = tmpsum % 2;
            char s = add + '0';
            res.insert(res.begin(),1,s);
        }
        if(cnt==1){
            res.insert(res.begin(),1,'1');
        }
        	//reverse(res.begin(), res.end());
        return res;
    }
};

Rust实现

use std::char::from_digit;
impl Solution {
    pub fn add_binary(a: String, b: String) -> String {
        let mut buf = Vec::with_capacity(usize::max(a.len(), b.len()) + 1);
        let mut a: Vec<char> = a.chars().collect();
        let mut b: Vec<char> = b.chars().collect();
        let mut carry = 0;
        while !(a.is_empty() && b.is_empty()) {
            let mut sum = a.pop().map_or(0, |ch| ch.to_digit(10).unwrap())
                + b.pop().map_or(0, |ch| ch.to_digit(10).unwrap())
                + carry;
            if sum > 1 {
                sum -= 2;
                carry = 1;
            } else {
                carry = 0;
            }
            buf.push(from_digit(sum, 10).unwrap())
        }
        if carry > 0 {
            buf.push('1')
        }
        buf.into_iter().rev().collect()
    }
}

结果

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

图解AI

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值