f

Sum(Large)

Sum(Large) || Newton school assignments solution in java

 || newton school assignments questions || newton school assignments

 problems solution

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

String Basics - Post Class - Sum(Large)

 Sum(Large)


Time Limit: 2 sec Memory Limit: 128000 kB Problem Statement Given two integers a and b your task is to print the summation of these two numbers Input Input contains a single line containing two space separated integers a and b. Constraints:- 1 <= a, b <= 1020000 Output Print the sum of a and b.

Example:


Sample Input:-
3 8

Sample Output:-
11

Sample Input:-
15 1

Sample Output:-
16


Solutions


import java.io.*; // for handling input/output

import java.util.*; // contains Collections framework

// don't change the name of this class
// you can add inner classes if needed
class Main {
    public static void main (String[] args) {
                      // Your code here
Scanner sc = new Scanner(System.in);
        String s1 = sc.next();
        String s2 = sc.next();
        int n= s1.length();
        int m= s2.length();

        int i=n-1 , j=m-1 , carry=0 , lastdigit , addition ;
        String result = "";

        while(i>=0 && j>=0){
            addition = s1.charAt(i)-'0' + s2.charAt(j)-'0'  + carry ;
            lastdigit = addition%10;
            carry = addition/10;
            result = lastdigit + result ;
            i--; 
            j--;            
        } 

        if(i==-1 && j==-1 && carry!=0){
            result = carry + result ;
        }else if(i>=0){
            while(carry!=0){
                if(i==-1){
                    result = carry + result ;
                    carry = 0;
                }
                else{
                addition = s1.charAt(i)-'0' + carry ;
                lastdigit = addition%10;
                carry = addition/10;
                result = lastdigit + result ;
                i--;
                }
            }
            if(i>=0){
                result = s1.substring(0,i+1) + result;
            }
        }
        else if(j>=0){
            while(carry!=0){
                if(j==-1){
                    result = carry + result ;
                    carry = 0;
                }
                else{
                    addition = s2.charAt(j)-'0' + carry ;
                lastdigit = addition%10;
                carry = addition/10;
                result = lastdigit + result ;
                j--;
                }
            }
            if(j>=0){
                result = s2.substring(0,j+1) + result;
            }
        }
        System.out.println(result); 
                  
    }
}
Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.