// 8ms
1 class Solution { 2 public: 3 string addBinary(string a, string b) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 reverse(a.begin(),a.end()); 7 reverse(b.begin(),b.end()); 8 int c=0; 9 string s; 10 int i; 11 12 for(i=0;(i<a.size())&&(i<b.size());i++) 13 { 14 s.append(1,(char)((a[i]-'0'+b[i]-'0'+c)%2+'0')); 15 c=(a[i]-'0'+b[i]-'0'+c)/2; 16 } 17 for(;i<a.size();i++) 18 { 19 s.append(1,(char)((a[i]-'0'+c)%2+'0')); 20 c=(a[i]-'0'+c)/2; 21 } 22 for(;i<b.size();i++) 23 { 24 s.append(1,(char)((b[i]-'0'+c)%2+'0')); 25 c=(b[i]-'0'+c)/2; 26 } 27 if(c==1) 28 s.append(1,'1'); 29 reverse(s.begin(),s.end()); 30 return s; 31 } 32 };