My code attempts to solve the leetcode problem of multiplying two strings containing positive integers. My code iterates through the digits of the first number and multiplies the current digit of the first number with the digit of the second number. It stores all the digits of each multiplication operation in a stack. However, I keep getting a null pointer exception for the line of code: aList[i].push("" + sum). I'm not sure what I'm doing wrong.
class Solution {
public String multiply(String num1, String num2) {
int len1 = num1.length();
int len2 = num2.length();
Stack[] aList = new Stack[len1];
int placeholder = 0;
for(int i = len1-1; i >= 0; i--) {
int n1 = num1.charAt(i) - '0'; //first digit
int carry = 0;
for(int z = 0; z < placeholder; z++) {
aList[i].push("" + 0); //add placeholder zeroes like in long multiplaction
}
for(int j = len2-1; j >= 0; j--) {
int n2 = num2.charAt(j) - '0'; //second digit
int sum = (n1 * n2) + carry;
carry = sum / 10; //holds the first digit for carrying to next multiply operation
sum = sum % 10; //holds the last digit of multiplaction for storage
aList[i].push("" + sum);
}
if(carry > 0) {
aList[i].push("" + carry); //add remaining carry value to string
}
placeholder++;
}
int result = 0;
for(int i = 0; i < aList.length; i++) {
String next = "";
for(int j = 0; j < aList[i].size(); j++) {
next += aList[i].peek(); //look at top digit and add to string
aList[i].pop(); //remove top digit
}
result += Integer.parseInt(next); //add finished sum to total
}
return Integer.toString(result);
}
}