本文主要是介绍力扣-415.字符串相加,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Idea
模拟:竖式加法
从后面往前逐位相加,然后将相加的结果模10,添加到答案字符串中去
最后需要判断一下是否还有进位问题
需要将答案string翻转
AC Code
class Solution {
public:string addStrings(string num1, string num2) {string ans;int l = num1.size() - 1, r = num2.size() - 1;int temp = 0;while(l >= 0 && r >= 0) {int a = num1[l] - '0';int b = num2[r] - '0';temp += a + b;ans += to_string(temp % 10);temp /= 10;l--;r--;}while(l >= 0) {int a = num1[l--] - '0';temp += a;ans += to_string(temp % 10);temp /= 10;} while(r >= 0) {int b = num2[r--] - '0';temp += b;ans += to_string(temp % 10);temp /= 10;}if(temp) ans += to_string(temp);reverse(ans.begin(),ans.end());return ans;}
};
这篇关于力扣-415.字符串相加的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!