Topic describes

Their thinking

The sum of a string can be calculated from the last character of the string. Converting a character to a number can be achieved by subtracting the character 0. As long as the subscript is greater than or equal to 0 or the carry is not equal to 0, we enter the loop. If the temporary sum mod 2 is 0,res unshift(0) and vice versa unshift(1). Then change the value of the carry based on the relationship between sum and 2, and finally subtract one from the subscript.

var addBinary = function(a, b) {
  let l = a.length - 1;
  let r = b.length - 1;
  let carry = 0;
  let res = [];

  while (l >= 0 || r >= 0|| carry ! =0) {
    let c1 = l >= 0 ? a[l] - '0' : 0;
    let c2 = r >= 0 ? b[r] - '0' : 0;

    let sum = c1 + c2 + carry;
    if (sum % 2) {
      res.unshift(1);
    } else {
      res.unshift(0);
    }
    if (sum > 2) {
      carry = (sum % 2! =0)?1 : 0;
    } else if (sum > 0) {
      carry = (sum % 2! =0)?0 : 1;
    } else {
      carry = 0;
    }
    l--;
    r--;
  }
  return res.join(' ');
};
Copy the code

The title to reflect

The most important thing is not the number of questions, of course, the number of questions is very important. Summarizing different questions and obtaining general solutions to these questions is the core of the problem, just like this problem, and string addition, two numbers can be used to solve the problem.