415. Add Strings
来源:互联网 发布:安踏奥运去打破h5源码 编辑:程序博客网 时间:2024/06/01 14:56
这道题的类型和2.add two numbers 是一样的,只不过2的里面是2个list相加,这个是两个string相加。
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.
和leetcode 2 相似,遍历两个string,直到2个string都遍历完了,用一个sum记录当前的进位和剩余值,只是要注意string res每次加上去的是反过来的数,最后要reverse 一下。
还有一个问题是用 - ‘0’实现char和int 的转换
代码如下:
class Solution {public: string addStrings(string num1, string num2) { int sum = 0; int i = num1.size() - 1; int j = num2.size() - 1; string res = ""; while(i >=0 || j >= 0) { if (i >= 0) sum += num1[i] - '0';// 用 - ‘0’实现char和int的转换。 if (j >= 0) sum += num2[j] - '0'; res += sum % 10 + '0'; sum = sum / 10; i--; j--; } while (sum) { res += sum % 10 + '0'; sum = sum / 10; } reverse(res.begin(), res.end());// don't forget to reverse the string return res; }};
阅读全文