[LeetCode] Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
1 class Solution 2 { 3 public: 4 string addBinary(string a, string b) 5 { 6 string c; 7 int carry = 0; 8 int tmp = 0; 9 int size = max(a.size(), b.size()); 10 11 //逆序,更好处理 12 reverse(a.begin(), a.end()); 13 reverse(b.begin(), b.end()); 14 15 16 for(int i = 0; i < size ; i++) 17 { 18 int ta = 0; 19 int tb = 0; 20 if(i < a.size()) //越界处理 21 ta = a[i] - '0';//处理字符串 22 if(i < b.size()) //越界处理 23 tb = b[i] - '0';//处理字符串 24 25 tmp = ta + tb + carry; 26 c.insert(c.begin(), tmp % 2 + '0'); 27 carry = tmp / 2; 28 } 29 30 if(carry != 0) 31 c.insert(c.begin() ,'1'); 32 return c; 33 } 34 } ;