题目描述:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
解题方案:
1 class Solution { 2 public: 3 string addBinary(string a, string b) { 4 int LocationA = a.size() - 1; 5 int LocationB = b.size() - 1; 6 7 if (LocationA == -1) { 8 return b; 9 } 10 if (LocationB == -1) { 11 return a; 12 } 13 string result; 14 int carry = 0; 15 16 while((LocationA >= 0) && (LocationB >= 0)) { 17 int temp = ((a[LocationA] - '0') + (b[LocationB] - '0') + carry) % 2; 18 carry = ((a[LocationA] - '0') + (b[LocationB] - '0') + carry) / 2; 19 result.append(1, temp + '0'); 20 --LocationA; 21 --LocationB; 22 } 23 if (LocationA != -1) { 24 while(LocationA >= 0) { 25 int temp = ((a[LocationA] - '0') + carry) % 2; 26 carry = ((a[LocationA] - '0') + carry) / 2; 27 result.append(1, temp + '0'); 28 --LocationA; 29 } 30 } 31 if (LocationB != -1) { 32 while(LocationB >= 0) { 33 int temp = ((b[LocationB] - '0') + carry) % 2; 34 carry = ((b[LocationB] - '0') + carry) / 2; 35 result.append(1, temp + '0'); 36 --LocationB; 37 } 38 } 39 40 if (carry != 0) { 41 result.append(1, carry + '0'); 42 } 43 44 int i = 0; 45 int j = result.size() - 1; 46 //将字符串反转 47 while (i <= j) { 48 char temp = result[i]; 49 result[i] = result[j]; 50 result[j] = temp; 51 ++i; 52 --j; 53 } 54 return result; 55 } 56 };