Skip to content

415. 字符串相加 #37

Open
Open
@Geekhyt

Description

@Geekhyt

原题链接

  1. 模拟加法,先补 0 对齐。
  2. 从右往左做加法,计算当前位 +num1[i] + +num2[i] + carry,使用 + 号将字符转换成数字。
  3. 当前位:模10的结果 + res字符串。
  4. carry 代表是否进位。
  5. 如果 carry 等于 1,需要在 res 前添加 '1'。
const addStrings = (num1, num2) => {
  while (num1.length > num2.length) num2 = '0' + num2
  while (num1.length < num2.length) num1 = '0' + num1
  let res = '', carry = 0;
  for (let i = num1.length - 1; i >= 0; i--) {
    const sum = +num1[i] + +num2[i] + carry 
    res = sum % 10 + res                       
    carry = sum > 9 ? 1 : 0
  }
  return carry === 1 ? '1' + res : res
};
  • 时间复杂度: O(n)
  • 空间复杂度: O(1)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions