Given two binary strings, return their sum (also a binary string).
For example,
a =
b =
Return
Analysis:For example,
a =
"11"
b =
"1"
Return
"100"
.Starting from end of strings, we add corresponding two digits together. Need to consider the followings:
1) a variable to record if there's carry in each addition;
2) if there's carry when we reach the MSB of two binaries, need to append another digit 1 in front;
3) (option) we could add dummy '0's in front of the shorter string, such that the code is cleaner and easier to understand.
Code:
class Solution { public: string addBinary(string a, string b) { string c=""; int carry=0; int al=a.size(), bl=b.size(); int cl=max(al, bl); for (int i=0; i<cl; i++){ // add dummy 0s in front of shorter string int k1=i<al ? a[al-i-1]-'0':0; int k2=i<bl ? b[bl-i-1]-'0':0; c=to_string((k1+k2+carry)%2)+c; carry=(k1+k2+carry)/2; } // need to check the last carry return carry==1 ? "1"+c:c; } };
No comments:
Post a Comment