leetcode 67. ???????????????(Add Binary)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 67. ???????????????(Add Binary)相关的知识,希望对你有一定的参考价值。
?????????har pre turn ?????? ?????? leetcode ????????? bin empty
???????????????
??????????????????????????????????????????????????????????????????????????????
?????????????????????????????????????????? 1
??? 0
???
?????? 1:
??????: a = "11", b = "1"
??????: "100"
?????? 2:
??????: a = "1010", b = "1011"
??????: "10101"
?????????
class Solution {
public:
string addBinary(string a, string b) {
string res = "";
if(a.empty()){
res = b;
}else if(b.empty()){
res = a;
}else{
int sz1 = a.size();
int sz2 = b.size();
int i = sz1 - 1;
int j = sz2 - 1;
int carry = 0;
while(i >= 0 && j >= 0){
int digit = int(a[i] - ???0???) + int(b[j] - ???0???) + carry;
if(digit >= 2){
carry = 1;
digit -= 2;
}else{
carry = 0;
}
res += char(digit + ???0???);
i --;
j --;
}
while(i >= 0){
int digit = int(a[i] - ???0???) + carry;
if(digit >= 2){
carry = 1;
digit -= 2;
}else{
carry = 0;
}
res += char(digit + ???0???);
i --;
}
while(j >= 0){
int digit = int(b[j] - ???0???) + carry;
if(digit >= 2){
carry = 1;
digit -= 2;
}else{
carry = 0;
}
res += char(digit + ???0???);
j --;
}
if(carry != 0){
res += char(carry + ???0???);
}
res = string(res.rbegin(), res.rend());
}
return res;
}
};
以上是关于leetcode 67. ???????????????(Add Binary)的主要内容,如果未能解决你的问题,请参考以下文章