Binary Sum

Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 and 0.

Example

Input: a = "11", b = "1" Output: "100"
Input: a = "1010", b = "1011" Output: "10101"

Hints

  • Each string consists only of '0' or '1' characters.
  • 1 <= a.length, b.length <= 10^4.
  • The strings are not prefixed with leading zeros except for the string "0".

Solution

/**
 * @param {string} a
 * @param {string} b
 * @return {string}
 */
var addBinary = function(a, b) {
    var longer = "";
    var shorter = "";
    if(a.length > b.length){
        longer = a;
        shorter = b.padStart(a.length,0);
    }else{
        longer = a.padStart(b.length,0);
        shorter = b;
    }
    var target = "";
    var addition = 0;
    for(let i=longer.length-1;i>=0;--i){
        let unitNum = ~~(longer[i]) + ~~(shorter[i]) + addition;
        addition = 0;
        if(unitNum >= 2) {
            addition = 1;
            target = `${unitNum-2}${target}`;
        }else{
            target = `${unitNum}${target}`;
        }
    }
    if(addition) target = `1${target}`;
    return target;
};

Idea

First, you need to unify the lengths of the two strings. Determine the length of the two strings, then select the shorter string and pad it with '0' in front of the string, that is, use the String.prototype.padStart() method to pad it. Then define the target string and the carry flag variable. Then iterate through the strings from the end to the beginning, convert the characters in the strings to numbers, add them together, and add them to the carry variable. The ~~ is used to convert characters to numbers using bit manipulation. After the addition is complete, set the carry flag to 0, then determine if the character is greater than 2. If it is greater than or equal to 2, subtract 2 from the added character and set the carry flag to 1. If it is less than 2, simply concatenate the string, and then continually loop to complete the concatenation of the target string. If there is still a carry flag at the end, simply concatenate1 to the front of the target string and then return it.

Every Day One Task

https://github.com/WindrunnerMax/EveryDay

Source

https://leetcode-cn.com/problems/add-binary