415. Add Strings(第十周)
来源:互联网 发布:工厂网络监控系统方案 编辑:程序博客网 时间:2024/06/03 16:44
Description
Add Strings - LeetCode
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
- The length of both
num1
andnum2
is < 5100. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
Input: "0", "0"
Output: "0"
Solution
这个是要我们模拟平时手算加法的方法。我们可以从string
的最后一位开始,从后往前加,如果某一个string
已经遍历到了开头,那么就不用加上它。最后就是进位的问题,如果加到最后还有进位的话,那么就要把进位也放到结果中去。
至于结果,我们可以先顺序存放计算的结果,然后最后把他进行一次reverse
操作即可得到答案
代码如下:
Source Code
submission
class Solution {public: string addStrings(string num1, string num2) { int i = num1.size() - 1; int j = num2.size() - 1; int carry = 0; string res = ""; while (i >= 0 || j >= 0 || carry) { long sum = 0; if (i >= 0) { sum += num1[i] - '0'; i--; } if (j >= 0) { sum += num2[j] - '0'; j--; } sum += carry; carry = sum / 10; sum = sum % 10; res = res + to_string(sum); } reverse(res.begin(), res.end()); return res; }};
阅读全文
0 0
- 415. Add Strings(第十周)
- LeetCode 415. Add Strings 题解(C++)
- 415. Add Strings
- Leetcode-415. Add Strings
- 415. Add Strings
- 415. Add Strings
- 415. Add Strings
- 415. Add Strings
- LeetCode 415. Add Strings
- 415. Add Strings
- 415. Add Strings
- [LeetCode]--415. Add Strings
- LeetCode 415. Add Strings
- LeetCode 415. Add Strings
- 415. Add Strings
- LeetCode 415. Add Strings
- 415. Add Strings
- 415. Add Strings
- Android 实现View滑动几种方式
- 浅谈总线通信机制---I2C总线接口
- Linux各个目录的作用及内容
- BCD码
- [java]什么是递归调用?(Recursion)
- 415. Add Strings(第十周)
- 算法学习入门书籍
- 华为USG2000/5000/6000系列批量端口映射
- 线性渲染(Linear Rendering)和Gamma Correction
- vim插件2--autocomplpop
- 根据后序遍历序列和中序遍历序列求前序遍历序列
- Qt的鼠标移入移出事件
- 使用Acrobat时,怎样使其默认页面显示方式为启用滚动
- 【zookeeper】事件 watch 机制 原理