Sum of two numbers where one number is represented as array of digits in C++

C++Server Side ProgrammingProgramming

In this problem, we are given two numbers, from which one is represented using array of digits. Our task is to create a program that will find the sum of two numbers where one number is represented as array of digits.

Let’s take an example to understand the problem,

Input: n = 213, m[] = {1, 5, 8, }
Output: 371
Explanation: 213 + 158 = 371

To solve this problem, we will simply digit by digit from the number which element of the array. It lsb of the number is added to the (n-1)th element of the array. The carry will be propagated for the next sum.

Example

Program to illustrate the working of our solution,

 Live Demo

#include <iostream>
using namespace std;
void addNumbers(int n, int size, int *m){
   int carry = 0;
   int sum = 0;
   for(int i = size-1; i >= 0; i--){
      sum = (n%10) + m[i] + carry;
      n /= 10;
      carry = sum/10;
      m[i] = sum%10;
   }  
}
int main() {
   int n= 679;
   int m[] = {1, 9, 5, 7, 1, 9};
   int size = sizeof(m)/sizeof(m[0]);
   cout<<"The sum of two numbers where one number is represented as array of digits is ";
   addNumbers(n, size, m);
   for(int i = 0; i < size; i++)
      cout<<m[i];
}

Output

The sum of two numbers where one number is represented as array of digits is 196398
raja
Published on 17-Aug-2020 10:42:06
Advertisements