Issue
My code is supposed to add two strings containing positive integers. It iterates through both strings and adds up the digits starting from the ends of the two strings as you would in normal addition. It stores the digits in a stack and the stack is converted to a string. When I run the code, I get an index out of range exception pointing to the line: while(num1.charAt(i) - '0' >= 0 && num2.charAt(j) - '0' >= 0)
. I'm not sure what I did wrong.
class Solution {
public String addStrings(String num1, String num2) {
int i = num1.length() - 1;
int j = num2.length() - 1;
int carry = 0;
int sum = 0;
Stack<Integer> result = new Stack<Integer>();
while(num1.charAt(i) - '0' >= 0 && num2.charAt(j) - '0' >= 0) {
int n1 = num1.charAt(i) - '0';
int n2 = num2.charAt(j) - '0';
sum = n1 + n2 + carry;
carry = sum / 10;
result.push(sum % 10);
i--;
j--;
}
if(num1.length() > num2.length()) {
i = num1.length() - num2.length() - 1;
while(num1.charAt(i) - '0' >= 0) {
int n = num1.charAt(i) - '0';
sum = n + carry;
carry = sum / 10;
result.push(sum % 10);
i--;
}
}
else if(num2.length() > num1.length()) {
i = num2.length() - num1.length() - 1;
while(num2.charAt(i) - '0' >= 0) {
int n = num2.charAt(i) - '0';
sum = n + carry;
carry = sum / 10;
result.push(sum % 10);
i--;
}
}
else if(carry > 0 && num1.length() == num2.length()) {
result.push(carry);
}
String ret = "";
for(int x = 0; x < result.size(); x++) {
ret += result.peek();
result.pop();
}
return ret;
}
}
Solution
Because you are looping and doing
i--;
j--;
then at some point you are calling while(num1.charAt(-1) - '0' >= 0 && ...
the quick solution is to test that i
and j
are greater than -1
in your loop.
while(i >= 0 && j >= 0 && num1.charAt(i) - '0' >= 0 && num2.charAt(j) - '0' >= 0) {
Answered By - Scary Wombat