題目描述 二進制求和
給定兩個二進制字符串,返回他們的和(用二進制表示)。
輸入為非空字符串且只包含數(shù)字 1 和 0。
示例 1:
輸入: a = "11", b = "1"
輸出: "100"
示例 2:
輸入: a = "1010", b = "1011"
輸出: "10101"
解題思路
思路是那個思路,寫的也太麻煩了,哎,啥時候才能學會??!沒關(guān)系,已經(jīng)學會一半了,至少知道先把短的字符串用0補齊了,但是下次能不用那么多if-else嗎,請講究技巧。
代碼
class Solution {
public:
string addBinary(string a, string b) {
string res="";
bool temp=false;
int i=a.size()-1;
int j=b.size()-1;
while(i>=0||j>=0){
int t;
if(i>=0 && j>=0) t = a[i] - '0' + b[j] - '0';
else if(i>=0) t = a[i] - '0';
else if(j>=0) t = b[j] - '0';
cout << "t:" << t << endl;
if(temp && t==2){
res = '1' + res;
}else if(temp && t==1){
res = '0' + res;
}else if(temp && t==0){
temp = false;
res = '1' + res;
}else if(!temp && t==2){
temp = true;
res = '0' + res;
}else if(!temp && t==1){
res = '1' + res;
}else if(!temp && t==0){
res = '0' + res;
}
i--;
j--;
}
if(temp) res = '1' + res;
return res;
}
};
祭出大佬代碼
class Solution {
public:
string addBinary(string a, string b) {
string res = "";
int c = 0;
int i = a.size() - 1;
int j = b.size() - 1;
while(i >= 0 || j>=0 || c==1){
c += (i>=0 ? a[i--] - '0':0);
c += (j>=0 ? b[j--] - '0':0);
res = char(c%2 + '0') + res;
c /= 2;
}
return res;
}
};