【发布时间】:2022-01-04 23:52:13
【问题描述】:
我的代码应该添加两个包含正整数的字符串。它遍历两个字符串并从两个字符串的末尾开始将数字相加,就像在正常加法中一样。它将数字存储在堆栈中,并将堆栈转换为字符串。当我运行代码时,我得到一个指向该行的索引超出范围异常:while(num1.charAt(i) - '0' >= 0 && num2.charAt(j) - '0' >= 0)。我不确定我做错了什么。
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;
}
}
【问题讨论】:
-
charAt()返回StringIndexOutOfBoundsException,如果给定的索引号大于或等于此字符串长度或负数。
标签: java stack indexoutofboundsexception subtraction addition