ADD Binary
The meaning of this question is relatively clear, the calculation of two string representation of the binary number of the addition, you can refer to the example to see, the meaning is still clearer.
My idea is to calculate from right to left, and put them in a new string, the main thing is to handle the carry, carry processing needs to be processed, I cite the corresponding examples of the following:
(1). "Ten" + "one" the two strings are the same length, so after the final addition, there is a final carry to be processed.
(2). "1" + "111" These two strings are of unequal length, so after processing one string, you still need to handle the other string separately.
The last thing to do is to reverse the string and get the final result.
It is time for you to solve this problem by analyzing the situation of carry, so let's take a look at my code.
Class Solution {Public:string addbinary (string A, string b) {string ret = ""; int len1 = A.size (); int len2 = B.size ();//empty string if (Len1 = = 0 && Len2 = = 0) return ret;//, a non-empty if (Len1 = = 0) return b;if (len2 = 0) return A; Record carry information for the next bit of processing int carrybit = 0; while (len1 > 0 && len2 > 0) {int bit = a[len1-1]-' 0 ' + b[len2-1]-' 0 '; if (carrybit = = 1) bit + = 1;//processing Carry if (bit > 1) {carrybit = 1;bit%= 2;ret.push_back (bit + ' 0 ');} Else{carrybit = 0;ret.push_back (bit + ' 0 ');} --len1;--len2;} Two strings are likely to be of unequal length while (len1--) {int bit = A[len1]-' 0 '; if (carrybit = = 1) bit + 1;if (bit > 1) {carrybit = 1;bit%= 2;} else{carrybit = 0;} Ret.push_back (bit + ' 0 ');} while (len2--) {int bit = B[len2]-' 0 ', if (carrybit = = 1) bit + = 1;if (bit > 1) {carrybit = 1;bit%= 2;} else{carrybit = 0;} Ret.push_back (bit + ' 0 ');} According to the above idea, the final carry is not processed and needs to be handled separately if (len1 <= 0 && len2 <= 0) {if (carrybit = 1) ret.push_back (' 1 ');} Reverse ret, get the correct result int begin = 0;int end = Ret.size () -1;wHile (begin < End) Swap (ret[begin++], ret[end--]); return ret;}};
Written question 80. Leetcode OJ (67)