给你两个二进制字符串,返回它们的和(用二进制表示)。
输入为 非空 字符串且只包含数字 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()
}
}
结果