Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Today comes a common question string addition, I have encountered in several interviews, such as degree of small full, good future and so on

415. String addition

Given two non-negative integers num1 and num2 in string form, evaluate their sum and return the same as a string. You can’t use any built-in libraries for handling large integers (such as BigInteger), nor can you directly convert an input string to an integer.

Source: LeetCode link: leetcode-cn.com/problems/ad…

Answer key

The idea is that the string iterates backwards and forwards, and then simulates addition

/ * * *@param {string} num1
 * @param {string} num2
 * @return {string}* /
var addStrings = function(num1, num2) {
    let add = 0
    let i = num1.length - 1
    let j = num2.length - 1
    
    let result = []
    while(i >= 0 || j >= 0|| add ! = =0) {let x = num1[i] ? +num1[i] : 0
        let y = num2[j] ? +num2[j] : 0 
        
        let res = x + y + add
        
        // result.unshift(res % 10)
        result.push(res % 10)
        add = ~~(res / 10)
        i--
        j--
    }
    // return result.join('')
    return result.reverse().join(' ')};Copy the code

Note that instead of using unshift, push + reverse is used for efficiency reasons

Efficiency comparison between unshift and push

Finally, let’s briefly test the efficiency of unshift and push in JavaScript

let arr = [];
let start = new Date(a);for (let i = 0; i < 100000; i++) {
  arr.push(i);
}

console.log(` push time:The ${new Date() - start}`);

arr = [];
start = new Date(a);for (let i = 0; i < 100000; i++) {
  arr.unshift(i);
}

console.log(` unshift time-consuming:The ${new Date() - start}`);
Copy the code

Test in node environment

Test in a browser environment