Microsoft Interview Question
I think linked list is better than string or arrays.
struct Node {
byte digit;
Node next;
}
For adding and subtracting, you just need to add a new node in the list that keeps the sum.
For multiplying and division, I would create 2 new lists where I keep the temporary results and the final.
class operation
{
public static void main(String[] args)
{
ArrayList<Integer> no1=new ArrayList<Integer>();
ArrayList<Integer> no2=new ArrayList<Integer>();
String n1="1231231231242342342342342342";
String n2="122342345657568678678562342342";
int c=0;
while(c<n1.length())
{
no1.add(Integer.parseInt(n1.substring(c,c)));
c++;
}
c=0;
while(c<n2.length())
{
no2.add(Integer.parseInt(n2.substring(c,c)));
c++;
}
add(no1,no2);
}
public static void add(ArrayList<Integer> no1, ArrayList<Integer> no2)
{int temp=0, c;
ArrayList<Integer> no3=new ArrayList<Integer>();
while(c<no1.length() && c<no2.length())
{
no3.add((no1.get(c)+no2.get(c)+temp)%10);
temp=(no1.get(c)+no2.get(c))/10;
}
if(c<no2.length())
while(c<no2.length())
{
no3.add((no2.get(c)+temp)%10);
temp=0;
}
if(c<no1.length())
while(c<no1.length())
{
no3.add((no1.get(c)+temp)%10);
temp=0;
}
}
class operation
{
public static void main(String[] args)
{
ArrayList<Integer> no1=new ArrayList<Integer>();
ArrayList<Integer> no2=new ArrayList<Integer>();
String n1="1231231231242342342342342342";
String n2="122342345657568678678562342342";
int c=0;
while(c<n1.length())
{
no1.add(Integer.parseInt(n1.substring(c,c)));
c++;
}
c=0;
while(c<n2.length())
{
no2.add(Integer.parseInt(n2.substring(c,c)));
c++;
}
add(no1,no2);
}
public static void add(ArrayList<Integer> no1, ArrayList<Integer> no2)
{int temp=0, c;
ArrayList<Integer> no3=new ArrayList<Integer>();
while(c<no1.length() && c<no2.length())
{
no3.add((no1.get(c)+no2.get(c)+temp)%10);
temp=(no1.get(c)+no2.get(c))/10;
}
if(c<no2.length())
while(c<no2.length())
{
no3.add((no2.get(c)+temp)%10);
temp=0;
}
if(c<no1.length())
while(c<no1.length())
{
no3.add((no1.get(c)+temp)%10);
temp=0;
}
}
This q haunted me for sometime as designing a BigInt class is tremendous effort.
- pk July 13, 2010for interview I would start with
string firstNum="11231234454567900707070978989678967896789";
string secondNum="11231234454567900707070978989678967896789";
Now write your own Adder (remember 3 rd grade mathematics)
Now write your own Subtract(again use same logic)
string Add(string n1,string n2)
string Sub(string n1,string n2)
Now you can easily write Multiply and Division routine.
By taking some more pain, you can extend it for decimal numbers.
There should exist a better and efficient method.
But this "MIGHT" save your day. :D