标签:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
[Solution]
1 string addBinary(string a, string b) 2 { 3 if (a.size() == 0) 4 return b; 5 if (b.size() == 0) 6 return a; 7 8 reverse(a.begin(), a.end()); 9 reverse(b.begin(), b.end()); 10 int carry = 0, i = 0; 11 string c = ""; 12 while (i < a.size() || i < b.size()) 13 { 14 int x = (i < a.size()) ? (a[i] - ‘0‘) : 0; 15 int y = (i < b.size()) ? (b[i] - ‘0‘) : 0; 16 if ((x + y + carry) & 1) 17 c += "1"; 18 else 19 c += "0"; 20 carry = (x + y + carry) >> 1; 21 i++; 22 } 23 if (carry > 0) 24 c += "1"; 25 reverse(c.begin(), c.end()); 26 27 return c; 28 }
标签:
原文地址:http://www.cnblogs.com/ym65536/p/4320659.html