Binary addition is essentially a big integer addition. My roommates have taught me a good way to add big integers. They first save the result with an int array and add the two numbers to the corresponding positions, after all are added, the carry problem is processed in a unified manner. This method also applies to multiplication of large integers.
There is nothing special about this question. Pay attention to the wrong carry. In addition, you don't have to worry about it. You can determine which one is longer at the beginning and exchange it. The code is much simpler.
class Solution {public: string addBinary(string a, string b) { int l1 = a.length(), l2 = b.length(); string c(max(l1, l2)+1, '0'); int i1 = l1-1, i2 = l2-1, ch=0, k = max(l1, l2); while(i1>=0&&i2>=0){ if(a[i1] == '1' && b[i2] == '1'){ c[k--] = ch+'0'; ch = 1; }else if(a[i1]=='1'||b[i2]=='1'){ if(ch){ c[k--] = '0'; }else{ c[k--] = '1'; } }else{ c[k--] = '0'+ch; ch = 0; } i1--; i2--; } while(i1>=0){ if(ch){ if(a[i1] == '1'){ c[k--] = '0'; ch = 1; }else{ c[k--] = '1'; ch = 0; } }else{ c[k--] = a[i1]; } i1--; } while(i2>=0){ if(ch){ if(b[i2] == '1'){ c[k--] = '0'; ch = 1; }else{ c[k--] = '1'; ch = 0; } }else{ c[k--] = b[i2]; } i2--; } if(ch) c[0] = '1'; if(c[0] == '0') c = c.substr(1, c.length()-1); return c; }};