问题描述
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b ="1"
Return"100"
.
题目链接
思路分析
对两个用string格式存储的二进制数进行加和,返回一个二进制数。思路是比对两个字符串的长度,然后直接对长的字符串进行修改,逢二进一,一直到字符串头。如果还有进位,就在前面再加一即可。
代码
class Solution {
public:
string addBinary(string a, string b) {
int carry = 0, sum;
int i = a.length() - 1;
int j = b.length() - 1;
if (i < j)
return addBinary(b,a);
while(i >= 0){
if (j >= 0)
sum = (a[i] - '0') + (b[j] - '0') + carry;
else
sum = (a[i] - '0') + carry;
if (sum == 3){
carry = 1;
a[i] = '1';
}
else if (sum == 2){
carry = 1;
a[i] = '0';
}
else if (sum == 1){
carry = 0;
a[i] = '1';
}
else{
carry = 0;
a[i] = '0';
}
i--;
j--;
}
if (carry == 1)
a = '1' + a;
return a;
}
};
时间复杂度:O(n) //n为长字符串的长度
反思
思考了很久,主要是对于进位的处理没有想清楚。对于字符的处理,实际上他是以ASCII码的形式存储的,可以直接进行加减运算的。