Add two numbers represented by two arrays | Practice | GeeksforGeeks

Given two array A[0....N-1] and B[0....M-1] of size N and M respectively, representing two numbers such that every element of arrays represent a digit. For example, A[] = { 1, 2, 3} and B[] = { 2, 1, 4 } represent 123 and 214 respectively. The task is to find the sum of both the numbers.
Example 1:
Input : A[] = {1, 2}, B[] = {2, 1}
Output : 33
Explanation:
N=2, and A[]={1,2}
M=2, and B[]={2,1}
Number represented by first array is 12.
Number represented by second array is 21
Sum=12+21=33
 
Example 2:
Input : A[] = {9, 5, 4, 9}, B[] = {2, 1, 4} 
Output : 9763 

Your Task:
This is a function problem. The input is already taken care of by the driver code. You only need to complete the function calc_Sum() that takes an array (a), sizeOfArray (n), an array (b), sizeOfArray (m), and return the sum . The driver code takes care of the printing.
Expected Time Complexity: O(N + M).
Expected Auxiliary Space: O(N + M).
 
Constraints:
2 ≤ N ≤ 105
2 ≤ M ≤ 105
0
rajubugude2 months ago
PYTHON CODE
class Solution:
    def helperAdd(self,a,b,n,m):
        sum = ''
        i = n - 1
        j = m - 1
        carry = 0
        while j >= 0:
            s = a[i] + b[j] + carry
            sum += str(s % 10)
            carry = s // 10
            i -= 1
            j -= 1
    
        while i >= 0:
            s = a[i] + carry
            sum += str(s % 10)
            carry = s // 10
            i -= 1
    
        if carry == 1:
            sum += str(carry)
        return int(sum[::-1])
        
        
    def calc_Sum (self, a1,  n1, a2, n2): 
        if n1 < n2:
            return self.helperAdd(a2,a1,n2,n1)
        return self.helperAdd(a1,a2,n1,n2)
+1
prasadchaskar2 months ago
Python Code:
def calc_Sum (self, arr,  n, brr, m) : 
        #Complete the function
        f = ""
        s = ""
        for i in arr:
            f += str(i)
        for i in brr:
            s += str(i)
        return int(f) + int(s)
0
sagrikasoni3 months ago
Java Code
class Solution{
    
  
    String calc_Sum(int a[], int n, int b[], int m)
    {
       int i = a.length-1, j = b.length-1; int sum =0, carry =0; String ans = "";
       while(i>=0 || j>=0){
           int x = (i>=0?a[i]:0);
           int y = (j>=0?b[j]:0);
           sum = carry + x+y;
           carry = sum>=10 ? 1:0;
           sum = sum%10;
           ans = ans + Integer.toString(sum);
           i--;
           j--;
       }
       if(carry>0){
           ans= ans + Integer.toString(carry);
       }
       StringBuffer s = new StringBuffer(ans);
         s.reverse();
         String res = s.toString();
         int curr =0;
         while(curr<res.length()&&res.charAt(curr)=='0'){
             curr++;
         }
         return res.substring(curr);
    }
  
    
}
0
yashpatil710973 months ago
int size=Math.max(n,m);        int []c= new int[size+1];        Arrays.fill(c,-1);        int sizea=0;        int sizeb=0;        for(int p=0;p<n;p++)        {            if(a[p]!=0)            {                sizea=p;                break;            }        }        for(int p=0;p<m;p++)        {            if(b[p]!=0)            {                sizeb=p;                break;            }        }        int i=n-1;        int j=m-1;        int count=c.length-1;        int carry=0;        while(i>=sizea&&j>=sizeb)        {           int temp=(a[i]+b[j]+carry);           c[count]=(temp%10);           carry=(temp/10);           count--;           i--;           j--;        }        while(i>=sizea)        {            int temp=(a[i]+carry);            c[count]=(temp%10);            carry=(temp/10);            count--;            i--;        }        while(j>=sizeb)        {            int temp=(b[j]+carry);            c[count]=(temp%10);            carry=(temp/10);            count--;            j--;        }        while(carry!=0)        {            int temp=(carry%10);            c[count]=temp;            count--;            carry=(carry/10);        }        String ans="";        for(int k=0;k<c.length;k++)        {            if(c[k]!=-1)            {                ans+=(c[k]);            }        }                return ans;
+1
afridikingkhan20175 months ago
//solve in java          
int as = 0;       for (int i = 0; i < a.length; i++) {           if (a[as] != 0) {               break;           }           as++;       }
       int bs = 0;       for (int i = 0; i < b.length; i++) {           if (b[bs] != 0) {               break;           }           bs++;       }       int ai = a.length - 1;       int bi = b.length - 1;       String sum = "";       int carry = 0;       while (ai >= as && bi >= bs) {           int currSum = a[ai] + b[bi] + carry;           carry = currSum / 10;           sum = (currSum % 10) + sum;           ai--;           bi--;       }       while (ai >= as) {           int currSum = a[ai] + carry;           carry = currSum / 10;           sum = (currSum % 10) + sum;           ai--;       }       while (bi >= bs) {           int currSum = b[bi] + carry;           carry = currSum / 10;           sum = (currSum % 10) + sum;           bi--;       }       if (carry != 0) sum = carry + sum;       return sum;   }   }
0
afridikingkhan2017
This comment was deleted.
0
Imran Wahid7 months ago
Imran Wahid
Easy C++ solution
class Solution{    public:    string calc_Sum(int *a,int n,int *b,int m)    {        int i=n-1,j=m-1,carry=0;        string ans="";        while(i>=0 || j>=0)        {            int sum=(i>=0?a[i--]:0)+(j>=0?b[j--]:0)+carry;            carry=sum/10;            ans+=to_string(sum%10);        }        if(carry)        {            ans+=to_string(carry);        }        reverse(ans.begin(),ans.end());        while(!ans.empty() && ans[0]=='0')        {            ans.erase(ans.begin());        }        return ans;    }};
 https://uploads.disquscdn.c...
0
Debojyoti Sinha11 months ago
Debojyoti Sinha
Correct Answer.Correct AnswerExecution Time:0.28
class Solution{    public:    string calc_Sum(int A[], int N, int B[], int M)    {        string res;                int carry = 0;                int i = N - 1;        int j = M - 1;                while(i >= 0 and j >= 0)        {            int sum = A[i] + B[j] + carry;                        res += (sum % 10) + '0';            carry = sum / 10;                        i--;            j--;        }                while(i >= 0)        {            int sum = A[i] + carry;                        res += (sum % 10) + '0';            carry = sum / 10;                        i--;        }                while(j >= 0)        {            int sum = B[j] + carry;                        res += (sum % 10) + '0';            carry = sum / 10;                        j--;        }                if(carry)        {            res += carry + '0';        }                reverse(res.begin(), res.end());                int curr = 0;        while(curr < res.size() and res[curr] == '0')        {            curr++;        }                return res.substr(curr);    }};
0
Ashish Agrawal11 months ago
Ashish Agrawal
Here is my solution,        na=''.join(map(str,arr))         nb=''.join(map(str,brr))
        return (int(na)+int(nb))
0
pratyush shekhar1 year ago
pratyush shekhar
PYTHON SOLUTIONdef calc_Sum (arr,  n, brr, m) :     str1=""    str2=""    for i in arr:        str1=str1+str(i)    for j in brr:        str2=str2+str(j)    sumi=int(str1)+int(str2)    return sumi
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.