原题链接:Leetcode 415. Add Strings
Given two non-negative integers, num1
and num2
represented as string, return the sum of num1 and num2 as a string.
You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.
Example 1:
Input: num1 = "11", num2 = "123"
Output: "134"
Example 2:
Input: num1 = "456", num2 = "77"
Output: "533"
Example 3:
Input: num1 = "0", num2 = "0"
Output: "0"
Constraints:
模拟竖式加法,用cf表示进位
问题是当两个数的位数不一样怎么办?
解决办法,允许下标到负数,给0就行。这样相当于加上了先导0,实现了两个数的位数相等
class Solution {
public:
string addStrings(string num1, string num2) {
// ij为两个指针, 初始指向末尾 cf为进位标志
int i = num1.size() - 1, j = num2.size() - 1, cf = 0;
string ans = "";
while(i >= 0 || j >= 0 || cf != 0){
int x = (i >= 0) ? num1[i] - '0' : 0;
int y = (j >= 0) ? num2[j] - '0' : 0;
// cnt当前位的和
int cnt = x + y + cf;
ans += ('0' + cnt % 10);
cf = cnt / 10;
i--;
j--;
}
// 翻转
reverse(ans.begin(), ans.end());
return ans;
}
};