415. Add Strings
Problem:
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
- The length of both num1 and num2 is < 5100.
- Both num1 and num2 contains only digits 0-9.
- Both num1 and num2 does not contain any leading zero.
- You must not use any built-in BigInteger library or convert the inputs to integer directly.
思路:
Solution (C++):
复制string addStrings(string num1, string num2) {
int m = num1.size() - 1, n = num2.size() - 1, carry = 0;
string res = "";
while (m >= 0 || n >= 0 || carry) {
long long sum = 0;
if (m >= 0) { sum += (num1[m--]-'0'); }
if (n >= 0) { sum += (num2[n--]-'0'); }
sum += carry;
carry = sum / 10;
sum %= 10;
res += to_string(sum);
}
reverse(res.begin(), res.end());
return res;
}
性能:
Runtime: 8 ms Memory Usage: 6.9 MB
思路:
Solution (C++):
性能:
Runtime: ms Memory Usage: MB
相关链接如下:
知乎:littledy
GitHub主页:https://github.com/littledy
github.io:https://littledy.github.io/
欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可
![](https://www.cnblogs.com/images/cnblogs_com/dysjtu1995/1468066/t_qrcode_for_gh_547d3edeac81_258.jpg)
作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步