Numbers Addition - Left to Right
Input Format:
The first line contains N1.
The second line contains N2.
Output Format:
The first line contains the sum of N1 and N2 added from left to right.
Boundary Conditions:
100 <= N1 <= 999999
100 <= N2 <= 999999
Example Input/Output 1:
Input:
6321
5235
Output:
1656
Example Input/Output 2:
Input:
16282
5964
Output:
11257
Code:
import java.util.*;
import java.math.*;
class sample
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
String s1=sc.next();
String s2=sc.next();
char[] ch=s1.toCharArray();
char[] ch1=s2.toCharArray();
String str="",str1="";
int i,n;
for(i=ch.length-1;i>=0;i--)
str+=ch[i];
for(i=ch1.length-1;i>=0;i--)
str1+=ch1[i];
if(str.length()!=str1.length())
{
n=Math.abs(str.length()-str1.length());
if(str.length()==str1.length()+n)
{
for(i=0;i<n;i++)
str1+='0';
}
else //if(str1.length()==str.length()+n)
for(i=0;i<n;i++)
str+='0';
}
int a=Integer.parseInt(str);
int b=Integer.parseInt(str1);
String res=Integer.toString(a+b);
for(i=res.length()-1;i>=0;i--)
System.out.print(res.charAt(i));
}
}
No comments:
Post a Comment