題目描述
給定兩個字符串形式的非負(fù)整數(shù) num1 和num2 ,計算它們的和。
注意:
num1 和num2 的長度都小于 5100.
num1 和num2 都只包含數(shù)字 0-9.
num1 和num2 都不包含任何前導(dǎo)零。
你不能使用任何內(nèi)建 BigInteger 庫, 也不能直接將輸入的字符串轉(zhuǎn)換為整數(shù)形式。
解題思路
雙指針
參考:https://leetcode-cn.com/problems/add-strings/solution/add-strings-shuang-zhi-zhen-fa-by-jyd/
代碼實現(xiàn)
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
class Solution {
public:
string addStrings(string num1, string num2) {
string res = "";
int i = num1.size() - 1, j = num2.size() - 1;
int carry = 0;
int n1 = 0, n2 = 0, tmp = 0;
while (i >= 0 || j >= 0) {
if (i >= 0) n1 = num1[i] - '0';
else n1 = 0;
if (j >= 0) n2 = num2[j] - '0';
else n2 = 0;
tmp = n1 + n2 + carry;
carry = tmp / 10;
res = to_string(tmp % 10) + res;
i--;
j--;
}
if (carry == 1) {
return "1" + res;
} else return res;
}
};