Given binary strings, return their sum (also a binary string).
For example,
A ="11"
b ="1"
Return "100"
.
My train of thought is:
1, the length of the two string is set to the same size, small to the left 0.
2, use Split ("") to split the string into an array.
3, set a carry indicator variable to add from right to left.
4, the array that holds the result is converted to a string using join ().
Code:
1 /**2 * @param {string} a3 * @param {string} b4 * @return {string}5 */6 varAddbinary =function(A, b) {7 varsum=[];8 varmaxlen=Math.max (a.length,b.length);9 varCount=0;TenA=a.split (""); OneB=b.split (""); A while(a.length<maxlen) - { -A.unshift (0); the } - while(b.length<maxlen) - { -B.unshift (0); + } - for(vari=maxlen-1;i>=0;i--) + { ASum[i]=number (A[i]) +number (B[i]) +count; at if(sum[i]>=2) - { -Sum[i]=sum[i]-2; -Count=1; - } - Else in { -Count=0; to } + } - if(count==1) the { *Sum.unshift (1); $ }Panax NotoginsengSum=sum.join (""); - returnsum; the};
View Code
Leetcode 67. ADD Binary