Sum of two large numbers in C++

C++Server Side ProgrammingProgramming

In this problem, we are given two string that defines two large numbers. Our task is to create a program to find the sum of two large numbers.

Let’s take an example to understand the problem,

Input: number1 = “341299123919”
number2 = “52413424”
Output: 341351537343

To solve this problem, we will traverse both the string. And add digit by digit and propagate the carry. And store the result digit by digit to sum string.

Algorithm

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.

Example

Program to illustrate the working of our solution,

#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;
}

Output

Sum of two large numbers is 280466644200


raja
Published on 17-Aug-2020 10:38:23
Advertisements