在这个问题中,我们得到了两个定义两个大数字的字符串。我们的任务是创建一个程序来查找两个大数的和。
Input: number1 = “341299123919” number2 = “52413424” Output: 341351537343
为了解决这个问题,我们将遍历这两个字符串。并逐位相加并传播进位。并逐位存储结果以求和。
Initialize sum = 0, carry = 0. Step 1: loop from n to 0. Step 1.1: intSum = number1[i] + number2[i] Step 1.2: carry = intSum/10. Sum += intSum Step 2: sum += carry. Step 3: return sum.
该程序说明了我们解决方案的工作原理,
#include<bits/stdc++.h> using namespace std; string addBigNumbers(string number1, string number2) { if (number1.length() > number2.length()) swap(number1, number2); string sum = ""; int len1 = number1.length(); int len2 = number2.length(); int digitDiff = len2 - len1; int carry = 0; int intSum; for (int i=len1-1; i>=0; i--) { intSum = ((number1[i]-'0') + (number2[i+digitDiff]- '0') + carry); sum.push_back(intSum%10 + '0'); carry = intSum/10; } for (int i=digitDiff-1; i>=0; i--) { intSum = ((number2[i]-'0')+carry); sum.push_back(intSum%10 + '0'); carry = intSum/10; } if (carry) sum.push_back(carry+'0'); reverse(sum.begin(), sum.end()); return sum; } int main() { string number1 = "235235823852"; string number2 = "45230820348"; cout<<"Sum of two large numbers is "<<addBigNumbers(number1,x number2); return 0; }
输出结果
Sum of two large numbers is 280466644200