Topic describes

Their thinking

Since we don’t want to use BigInt to convert strings to integers, we have to consider other methods. Therefore, the double-pointer method is considered in this case.

  1. Use two Pointers to the end of the numeric string.
  2. Use the variable carry to record the carry.
  3. Both records enter the loop when the position of the subscript is greater than or equal to zero, or when the carry is not equal to zero.
  4. When the charAt API is used to retrieve the subscript characters of the string in the loop, the subtraction of the two characters becomes the number type.
  5. Each end of the loop moves the two Pointers one to the left.

The problem solving code

var addStrings = function(num1, num2) {
    
    let l = num1.length - 1;
    let r = num2.length - 1;
    let carry = 0;
    let ans = [];
    while (l >= 0 || r >= 0|| carry ! = =0) {

        let c1 = l >= 0 ? num1.charAt(l) - '0' : 0;
        let c2 = r >= 0 ? num2.charAt(r) - '0' : 0;
        let sum = c1 + c2 +  carry;
        ans.push(sum % 10);
        carry = Math.floor(sum / 10);
        l--;
        r--;
    }
    return ans.reverse().join(' ')};Copy the code

The title to reflect

  1. Two numeric characters are converted to type number by subtracting them.
  2. You can use the string. CharAt (index) to get the character at the specified position in the string.