Multiply Big Numbers as Strings

public String multiply(String num1, String num2){
int product, carry=0, sum=0;
String result = new String(“”);
String partial = new String(“”);
ArrayList partialList = new ArrayList();

/* computing partial products using this loop. */
for(int j=num2.length()-1 ; j>=0 ; j–) {
for(int i=num1.length()-1 ; i>=0 ; i–) {

product = Integer.parseInt((new Character(num1.charAt(i))).toString()) *
Integer.parseInt((new Character(num2.charAt(j))).toString()) + carry;
carry = product/10;
partial = Integer.toString(product%10) + partial;
}

if(carry != 0)
partial = Integer.toString(carry) + partial;

partialList.add(partial);
partial = “”;
carry = 0;
}

/* appending zeroes incrementally */
for(int i=0 ; i=0 ; i–) {

sum = 0;
for(int j=0 ; j<partialList.size() ; j++)
sum = sum + Integer.parseInt(new Character(partialList.get(j).charAt(i)).toString());

sum = sum + carry;
carry = sum/10;
result = Integer.toString(sum%10) + result;
}

if(carry != 0)
result = Integer.toString(carry) + result;

return result;
}

Advertisements