Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
class Solution { public: string addBinary(string a, string b) { string sol; int len1=a.size(); int len2=b.size(); std::reverse(a.begin(),a.end()); std::reverse(b.begin(),b.end()); int i=0; int carry=0; while(i<len1&&i<len2) { int c=(a[i]-'0'+b[i]-'0'+carry)%2; carry=(a[i]-'0'+b[i]-'0'+carry)/2; sol.append(1,c+'0'); i++; } while(i<len1) { int c=(a[i]-'0'+carry)%2; carry=(a[i]-'0'+carry)/2; sol.append(1,c+'0'); i++; } while(i<len2) { int c=(b[i]-'0'+carry)%2; carry=(b[i]-'0'+carry)/2; sol.append(1,c+'0'); i++; } if(carry!=0)sol.append(1,'1'); std::reverse(sol.begin(),sol.end()); return sol; } };
class Solution { public: string addBinary(string a, string b) { string sol; if(b.size()>a.size()) { string t=a; a=b; b=t; } int len1=a.size(); int len2=b.size(); std::reverse(a.begin(),a.end()); std::reverse(b.begin(),b.end()); int i=0; int carry=0; while(i<len2) { int c=(a[i]-'0'+b[i]-'0'+carry)%2; carry=(a[i]-'0'+b[i]-'0'+carry)/2; sol.append(1,c+'0'); i++; } while(i<len1) { int c=(a[i]-'0'+carry)%2; carry=(a[i]-'0'+carry)/2; sol.append(1,c+'0'); i++; } if(carry!=0)sol.append(1,'1'); std::reverse(sol.begin(),sol.end()); return sol; } };
class Solution { public: string addBinary(string a, string b) { string sol; if(b.size()>a.size()) { string t=a; a=b; b=t; } int len1=a.size(); int len2=b.size(); std::reverse(a.begin(),a.end()); std::reverse(b.begin(),b.end()); int i=0; int carry=0; while(i<len2) { int c=(a[i]-'0'+b[i]-'0'+carry)%2; carry=(a[i]-'0'+b[i]-'0'+carry)/2; sol.append(1,c+'0'); i++; } while(i<len1) { int c=(a[i]-'0'+carry)%2; carry=(a[i]-'0'+carry)/2; sol.append(1,c+'0'); i++; } if(carry!=0)sol.append(1,'1'); std::reverse(sol.begin(),sol.end()); return sol; } };