标签:
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) { int lena=a.size(); int lenb=b.size(); if (lena==0)return b; if (lenb==0)return a; string c=""; int flag=0; while(lena>0&&lenb>0) { int temp=a[lena-1]-‘0‘+b[lenb-1]-‘0‘+flag; c=char(temp%2+‘0‘)+c; flag=temp/2; lena--; lenb--; } while(lena>0) { int temp=a[lena-1]-‘0‘+flag; c=char(temp%2+‘0‘)+c; flag=temp/2; lena--; } while(lenb>0) { int temp=b[lenb-1]-‘0‘+flag; c=char(temp%2+‘0‘)+c; flag=temp/2; lenb--; } if(flag>0)c=char(flag+‘0‘)+c; return c; } };
标签:
原文地址:http://www.cnblogs.com/Vae98Scilence/p/4281495.html