leetcode67. Add Binary
Posted yfceshi
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode67. Add Binary相关的知识,希望对你有一定的参考价值。
@requires_authorization
@author johnsondu
@create_time 2015.7.15 11:00
@url [add binary](https://leetcode.com/problems/add-binary/)
/*******************
* 模拟大数相加
* 时间复杂度: O(n)
* 空间复杂度: O(n)
******************/
class Solution {
public:
string addBinary(string a, string b) {
int lena = a.size();
int lenb = b.size();
string ans = "";
string tmpa = "";
string tmpb = "";
for(int i = lena-1; i >= 0; i --) tmpa += a[i];
for(int i = lenb-1; i >= 0; i --) tmpb += b[i];
int mins = min(lena, lenb);
int carry = 0;
for(int i = 0; i < mins; i ++){
int res = (tmpa[i] - ‘0‘) + (tmpb[i] - ‘0‘) + carry;
carry = res > 1 ? 1 : 0;
res = res % 2;
ans += (res + ‘0‘);
}
for(int i = mins; i < lena; i ++){
int res = (tmpa[i] - ‘0‘) + carry;
carry = res > 1 ?
1 : 0;
res = res % 2;
ans += (res + ‘0‘);
}
for(int i = mins; i < lenb; i ++){
int res = (tmpb[i] - ‘0‘) + carry;
carry = res > 1 ?
1 : 0;
res = res % 2;
ans += (res + ‘0‘);
}
if(carry){
ans += (carry + ‘0‘);
}
int len_ans = ans.size();
for(int i = 0; i < len_ans / 2; i ++){
char tmp = ans[i];
ans[i] = ans[len_ans-i-1];
ans[len_ans-i-1] = tmp;
}
return ans;
}
};
// Simplified Version
class Solution {
public:
string addBinary(string a, string b) {
int lena = a.size() - 1;
int lenb = b.size() - 1;
string ans = "";
int carry = 0;
while(lena >= 0 || lenb >= 0 || carry > 0){
int res = carry;
if(lena >= 0) res += (a[lena] - ‘0‘);
if(lenb >= 0) res += (b[lenb] - ‘0‘);
carry = res / 2;
ans = string(1, (res & 1) + ‘0‘) + ans;
lena --;
lenb --;
}
return ans;
}
};
以上是关于leetcode67. Add Binary的主要内容,如果未能解决你的问题,请参考以下文章