1. Topics
Given binary strings, return their sum (also a binary string).
For example,
A ="11"
b ="1"
Return "100"
.
2. Solutions
Class Solution {Public:char inttochar (int input) {char strbuffer[1] = {0}; sprintf (Strbuffer, "%d", input); return strbuffer[0]; } string Addb (string A, string b) {string result; for (int i = A.size ()-1; I >=0; i.) {int adigital = a[i]-' 0 '; int bdigital = b[i]-' 0 '; int sumresult = adigital + bdigital; if (Sumresult >= 2) {if (Sumresult = = 2) {result.push_back (' 0 '); }else{result.push_back (' 1 '); } if (i-1 >= 0) {a[i-1] = Inttochar (a[i-1]-' 0 ' + 1); }else{result.push_back (' 1 '); }}else{Result.push_back (Inttochar (Sumresult)); }} reverse (Result.begin (), Result.end ()); return result; } StRing Addbinary (String A, string b) {size_t Sizea = a.size (); size_t Sizeb = B.size (); Unequal alignment if (Sizea > Sizeb) {b.insert (B.begin (), Sizea-sizeb, ' 0 '); } else if (Sizea < Sizeb) {A.insert (A.begin (), Sizeb-si ZeA, ' 0 '); } return Addb (A, b); }};
1. Here are some tricks, the first is to put a short string in front of 0, using the Insert method. Then it is according to the manual addition method, starting from the last one, if greater than or equal to 2, the number of the previous digit plus 1. The final result is reversed. If you know that a char is a number, for example, to turn ' 9 ' into an int of 9, you can put ' 9 '-' 0 '.
http://www.waitingfy.com/archives/1686
Leetcode ADD Binary