Question
Link:https://leetcode.com/problems/add-binary/
Given two binary strings, return their sum (also a binary string).
For example,
a = “11”
b = “1”
Return “100”.
Code
一个比较挫的算法。(C++ :4ms)
class Solution {
public:
string addBinary(string a, string b) {
int len = a.size() > b.size() ? a.size() : b.size();
int carry = 0;
string result = "";
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
for(int i = 0; i < len; i++){
if(i >= a.size()){ //b is longer than a
if(b[i] == '1'){
if(carry == 1)
result.insert(0, "0", 0, 1);
else
result.insert(0, "1", 0, 1);
}
else{
if(carry == 1){
result.insert(0, "1", 0, 1);
carry = 0;
}
else
result.insert(0, "0", 0, 1);
}
}
else if(i >= b.size()){ //a is longer than b
if(a[i] == '1'){
if(carry == 1)
result.insert(0, "0", 0, 1);
else
result.insert(0, "1", 0, 1);
}
else{
if(carry == 1){
result.insert(0, "1", 0, 1);
carry = 0;
}
else
result.insert(0, "0", 0, 1);
}
}
else{
if(a[i] == '1' && b[i] == '1'){
if(carry == 1)
result.insert(0, "1", 0, 1);
else
result.insert(0, "0", 0, 1);
carry = 1;
}
else if(a[i] == '0' && b[i] == '0'){
if(carry == 0) // 0 + 0
result.insert(0, "0", 0, 1);
else
result.insert(0, "1", 0, 1);
carry = 0;
}
else{
if(carry == 0) // 1 + 0
result.insert(0, "1", 0, 1);
else // 1 + 0 + 1(carry)
result.insert(0, "0", 0, 1);
}
}
}
if(carry == 1)
result.insert(0, "1", 0, 1);
return result;
}
};