The idea was to add the binary numbers (represented as strings) from the back to forth bit by bit and store the result in t He longer string. After the shorter string have been added, we continue to handle the carry bit. We may need to append the carry bit to the beginning of the longer string if necessary.
The code is as follows.
1 classSolution {2 Public:3 stringAddbinary (stringAstringb) {4 intm = A.length (), n = b.length (), C =0, I, J;5 if(M < n)returnAddbinary (b, a);6 for(i = m-1, j = n-1; J >=0; I--, j--) {7 intAD = A[i]-'0', BD = B[j]-'0';8A[i] = (AD ^ BD ^ c) +'0';9c = (AD + bd + C >=2);Ten } One for(; I >=0; i--) { A intAD = A[i]-'0'; -A[i] = (ad ^ c) +'0'; -c = (AD + C >=2); the } - if(c) A ='1'+A; - returnA; - } +};
Running the above code on the simple example would help you get all its a = "1", b = "11" details (both the both for loops and the Statements'll be hit if ):-)
[Leetcode] ADD Binary