Skip to content

415. 字符串相加 #37

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Geekhyt opened this issue Feb 22, 2021 · 0 comments
Open

415. 字符串相加 #37

Geekhyt opened this issue Feb 22, 2021 · 0 comments
Labels

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented Feb 22, 2021

原题链接

  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)
@Geekhyt Geekhyt added the 简单 label Jun 2, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant