Sum of two numbers represented as arrays

PROBLEM :

Given two numbers represented by two arrays, write a function that returns sum array. The sum array is an array representation of addition of two input arrays. It is not allowed to modify the arrays.

Input:

The first line of input contains an integer T denoting the number of test cases.
The first line of each test case contains two integers M and N separated by a space. M is the size of arr1 and N is the size of arr2.
The second line of each test case contains M integers which is the input for arr1.
The third line of each test case contains N integers which is the input for arr2.

Output:

Print the sum list.

Constraints:

1 = T = 100
1 = N = M = 1000
0 = arr1[i],arr2[i]= 9

Example:

Input:
2
3 3
5 6 3
8 4 2
16 4
2 2 7 5 3 3 7 3 3 6 8 3 0 5 0 6
4 3 3 8

Output:
1 4 0 5
2 2 7 5 3 3 7 3 3 6 8 3 4 8 4 4

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

#include<iostream>
using namespace std;
int Sum_of_two_numbers(int [],int [],int [],int ,int ) ;
void reverse(int [],int ) ;
int main()
 {
int t,arr1[1000],arr2[1000],n1,n2,i ;
cin>>t ;
while(t--)
{
   cin>>n1>>n2 ;
 
   for(i=0;i<n1;i++)
       cin>>arr1[i] ;
   for(i=0;i<n2;i++)
       cin>>arr2[i]  ;
     
   int arr3[1001]={0} ;
 
   int no=Sum_of_two_numbers(arr1,arr2,arr3,n1,n2) ;
 
   reverse(arr3,no) ;
 
   for(i=0;i<=no;i++)
       cout<<arr3[i]<<" " ;
   cout<<endl ;
}
return 0;
}

int Sum_of_two_numbers(int a[],int b[],int c[],int n1,int n2)
{
    int k,carry ;
    k=0 ;
    carry=0 ;
   
    while(n1!=0&&n2!=0)
    {
        c[k]=a[--n1]+b[--n2]+carry ;
        carry=c[k]/10 ;
        c[k]=c[k]%10 ;
        k++ ;
    }
   
    if(n1!=0)
        while(n1!=0)
        {
            c[k]=a[--n1]+carry ;
            carry=c[k]/10 ;
            c[k]=c[k]%10 ;
            k++ ;
        }
       
    if(n2!=0)
        while(n2!=0)
        {
            c[k]=a[--n2]+carry ;
            carry=c[k]/10 ;
            c[k]=c[k]%10 ;
            k++ ;
        }
       
    if(carry!=0)
        c[k++]=carry ;
   
    return k-1 ;
}

void reverse(int arr[],int no)
{
    int i,j,temp ;
    i=0;
    j=no ;
   
    while(i<j)
    {
        temp=arr[i] ;
        arr[i]=arr[j] ;
        arr[j]=temp ;
        i++ ;
        j-- ;
    }
}                              

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )