Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
思路:
先将原字符串反转,对齐逐位进行相加,再把结果反转
1 string addBinary(string a, string b) { 2 // Note: The Solution object is instantiated only once and is reused by each test case. 3 reverse(a.begin(), a.end()); 4 reverse(b.begin(), b.end()); 5 int la = a.length(), lb = b.length(), n = min(la, lb); 6 int i, carry = 0, t; 7 string result = ""; 8 for(i = 0; i < n; i++){ 9 t = carry + a[i] + b[i] - '0' - '0'; 10 carry = t/2; 11 t = t%2; 12 result = result + (char)('0'+t); 13 } 14 if(la > lb){ 15 for(i = lb; i < la; i++){ 16 t = carry + a[i] - '0'; 17 carry = t/2; 18 t = t%2; 19 result = result + (char)('0'+t); 20 } 21 } 22 else{ 23 for(i = la; i < lb; i++){ 24 t = carry + b[i] - '0'; 25 carry = t/2; 26 t = t%2; 27 result = result + (char)('0'+t); 28 } 29 } 30 if(carry == 1) 31 result += '1'; 32 reverse(result.begin(), result.end()); 33 return result; 34 }