Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Thursday, September 7, 2017

Sum Of two Large Number Geeks


Problem :


Given two non-negative numbers X and Y. The task is calculate the sum of X and Y.
 if the number of digits in sum (X+Y) are equal to the number of digits in X, then print sum, else print X.


Explanation :

Idea is to either take string and write function to add two strings

OR

We can use BigInteger In Java and call add function to add two large Numbers


Code:


public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t-->0)
{
   BigInteger x=new BigInteger(ab.next());
   BigInteger y=new BigInteger(ab.next());
   BigInteger sum=x.add(y);
   if(String.valueOf(x).length()==String.valueOf(sum).length())
   System.out.println(String.valueOf(sum));
   else
   System.out.println(x);
}

Basic Logic without BIgInteger

   int i=a.length()-1,j=b.length()-1,k=0;
           int carry=0;
           while(i>=0&&j>=0)
           {
               arr[k]=((a[i]-'0')+(b[j]-'0')+carry)%10;
               carry=((a[i]-'0')+(b[j]-'0')+carry)/10;
               k++;
               i--;
               j--;
           }
           
           while(i>=0)
           {
               arr[k]=((a[i]-'0')+carry)%10;
               carry=((a[i]-'0')+carry)/10;
               k++;
               i--;
           }
           
           while(j>=0)
           {
               arr[k]=((b[i]-'0')+carry)%10;
               carry=((b[i]-'0')+carry)/10;
               k++;
               j--;
           }
           if(carry)
           {
               arr[k]=carry;
               k++;
           }
           
           if(k==a.length())
              for(i=k-1;i>=0;i--)
                 cout<<arr[i];
           else
               cout<<a;
           nxt;

       }

0 Comments:

Post a Comment

Stats