How to add two numbers of any length in java?
Say for example, in java long size is 64 bit. So the maximum range is -9223372036854775808 to 9223372036854775807. Am i
Create a stack class and get numbers as string from user and convert them into string and push them into stacks. Here I've written the full code for the addition of two large numbers. stack class also included. Just type in cmd javac mystack.java then java mystack
import java.util.*;
public class mystack {
int maxsize=0;
int top=-1;
int array []=new int [0];
public mystack (int size)
{
maxsize=size;
array=new int [maxsize];
}
public void push (int x)
{
top=top+1;
array[top]=x;
}
public int pop ()
{
int elt=array[top];
top--;
return elt;
}
public boolean stackisfull()
{
return(top==maxsize-1);
}
public boolean stackisempty()
{
return(top==-1);
}
public int peak ()
{
int peak =array[top];
return peak;
}
public static void main (String args[]){
Scanner in=new Scanner (System.in);
System.out.println("Enter the 1st number");
String number1 = in.nextLine();
System.out.println();
System.out.println("Enter the 2nd number");
String number2 = in.nextLine();
System.out.println();
String temp="";
if(number1.length()>number2.length())
{
temp=number1;
number1=number2;
number2=temp;
}
int k=0;
mystack S1 = new mystack (number1.length());
for(int i=0;i<number1.length();i++)
{
String str=Character.toString(number1.charAt(i));
S1.push(Integer.parseInt(str));
}
mystack S2 = new mystack (number2.length());
for(int i=0;i<number2.length();i++)
{
String str=Character.toString(number2.charAt(i));
S2.push(Integer.parseInt(str));
}
mystack S3 =new mystack (number2.length());
while(!S1.stackisempty())
{
int x=S1.pop();
int y=S2.pop();
int times=(x+y+k)/10; int remainder =(x+y+k)%10;
k=0;
if(times==0)
{
S3.push(remainder);
}
else
{
S3.push(remainder);
k=1;
}
}
while(!S2.stackisempty())
{
if(k==1)
{
S3.push(k+S2.pop());
k=0;
}
else
S3.push(S2.pop());
}
System.out.print("Addition is ");
while(!S3.stackisempty())
{
System.out.print(S3.pop());
}
}
}
import java.math.BigInteger;
import java.util.Scanner;
public class BigIntergerSumExample {
public static void main(String args[]) {
BigInteger number1;
BigInteger number2;
BigInteger sum;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of number 1");
number1 = sc.nextBigInteger();
System.out.println("Enter the value of number 2");
number2 = sc.nextBigInteger();
BigInteger a = new BigInteger(""+number1);
BigInteger b = new BigInteger(""+number2);
BigInteger result = a.add(b);
System.out.println("Sum is Two numbers : -> " + result);
}
}
**OUTPUT IS**
Enter the value of number 1
1111111111111111111111111111111111111111111111111
Enter the value of number 2
2222222222222222222222222222222222222222222222222
Sum is Two numbers : ->
3333333333333333333333333333333333333333333333333
import java.math.BigInteger will let you work with numbers of any size,