孙晓聪
  • 最新
  • 博客
  • 书评
  • Add Strings

    Dscription

    doc

    Solutions

    First Idea

    /**
     * @param {string} num1
     * @param {string} num2
     * @return {string}
     */
    var addStrings = function (num1, num2) {
      let k = (curry = 0)
    
      let nums = []
      let i = num1.length
      let j = num2.length
    
      while (i > 0 || j > 0) {
        const sum = +(num1[--i] ?? 0) + +(num2[--j] ?? 0) + curry
        curry = Math.floor(sum / 10)
        nums[k++] = sum % 10
      }
    
      if (curry) {
        nums[k] = curry
      }
    
      return nums.reverse().join('')
    }
    
    • Time Complexity: O(n)
    • Space Complexity: O(n)