没太明白你为什么要reverse+补0。联想Add Binary那道题就可以知道,这题是字符串
不是链表,字符串可以从后往前访问,所以完全可以不补0,直接从后往前访问。当某
一个字符串用光时,再处理另外一个字符串剩下的(注意进位),最后再看有没有多余
的一个进位。
毕竟你string是可以一直"push_front"的
Leetcode原题:
class Solution {
public:
string addBinary(string a, string b) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int aIndex = a.size() - 1, bIndex = b.size() - 1;
string res;
int carry = 0;
while( aIndex >= 0 && bIndex >= 0){
int local = carry + (a[aIndex] -'0') + (b[bIndex] - '0');
int sum = local%2;
carry = local/2;
char tmp = '0' + sum;
res = tmp + res;
aIndex--; bIndex--;
}
while( aIndex >= 0){
int local = carry + (a[aIndex] -'0');
int sum = local%2;
carry = local/2;
char tmp = '0' + sum;
res = tmp + res;
aIndex--;
}
while( bIndex >= 0){
int local = carry + (b[bIndex] -'0');
int sum = local%2;
carry = local/2;
char tmp = '0' + sum;
res = tmp + res;
bIndex--;
}
if( carry > 0){
char tmp = '0' + carry;
res = tmp + res;
}
return res;
}
};