Skip to content

Latest commit

 

History

History
58 lines (42 loc) · 1.59 KB

20200803-415.add-strings.md

File metadata and controls

58 lines (42 loc) · 1.59 KB

415.add-strings

题目链接:https://leetcode-cn.com/problems/add-strings/

参考链接:https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list/solution/er-cha-shu-zhan-kai-wei-lian-biao-by-leetcode-solu/

题目

给定两个字符串形式的非负整数 num1num2 ,计算它们的和。

注意:

  • num1 和num2 的长度都小于 5100.
  • num1 和num2 都只包含数字 0-9.
  • num1 和num2 都不包含任何前导零。
  • 你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。

解题

思路[1]暴力相加

  • 首先先将两个数进行补零,补到两者的最多位数+1(为了处理最高位+1)的问题
  • 从数的结尾进行遍历,找出对应为位,转化为数字,两个数相加,再加进位,然后记录是否进位
  • 最后返回时将没有处理的数字,和处理后的空白字符去除

代码

/**
 * @param {string} num1
 * @param {string} num2
 * @return {string}
 */
var addStrings = function(num1, num2) {
  let length = Math.max(num1.length, num2.length) + 1,
    i = length - 1,   
    num1Cache = num1.padStart(length, '0'),
    num2Cache = num2.padStart(length, '0'),
    base = 0, 
    res = '';
  while(i >= 0){
    let numItem1 = num1Cache.charAt(i) - '0';
    let numItem2 = num2Cache.charAt(i) - '0';
    let sum = `${numItem1 + numItem2 + base}`;
    res = `${sum[sum.length-1]}${res}`;
    base = sum.length - 1;
    i--;
  }
  return`${num1Cache.slice(1, i + 1)}${num2Cache.slice(1, i + 1)}${res.replace(/^0+/, '') || '0'}`
};

思考