C++
1 class Solution { 2 public: 3 /** 4 * @param a a number 5 * @param b a number 6 * @return the result 7 */ 8 string addBinary(string& a, string& b) { 9 // Write your code here10 if (a == "0") {11 return b;12 }13 if (b == "0") {14 return a;15 }16 string result;17 int carry = 0;18 int ai, bj, sum;19 char val;20 for (int i = a.size()-1, j = b.size()-1; i >= 0 || j >= 0; i--, j--) {21 ai = i >= 0?a[i]-'0':0;22 bj = j >= 0?b[j]-'0':0;23 sum = ai+bj+carry;24 val = sum%2?'1':'0';25 carry = sum/2;26 result.insert(result.begin(), val);27 }28 if (carry == 1) {29 result.insert(result.begin(), '1');30 }31 return result;32 }33 };