Title:
Given binary strings, return their sum (also a binary string).
For example,
A ="11"
b ="1"
Return "100" .
Tips:
My first reaction to this question is to convert the input two string into a number, add the result into a binary output, but there will be a lot of input in the test case, even if a long long type can also cause overflow, so can only use the most traditional from low to high position to add the method to do.
Code:
classSolution { Public: stringAddbinary (stringAstringb) {intLen_a = A.size ()-1, Len_b = B.size ()-1; intDIF = ABS (Len_a-Len_b); stringPrev =""; for(inti =0; i < dif; ++i) Prev + ='0'; if(Len_a < Len_b) A = prev +A; Elseb = prev +b; intLen = a.size (), step =0; Vector<int>v; for(inti = len-1; I >-1; --i) {step+ = A[i] + b[i]-('0'<<1); V.push_back (Step%2); Step= Step >>1; } if(step) v.push_back (step%2); stringRes; for(inti = v.size ()-1; I >-1; --i) {res+= ('0'+V[i]); } returnRes; }};
"Leetcode" 67. ADD Binary