我的代碼應該添加兩個包含正整數的字串。它遍歷兩個字串,并將從兩個字串末尾開始的數字相加,就像您在正常加法中所做的那樣。它將數字存盤在堆疊中,并將堆疊轉換為字串。當我運行代碼時,我得到一個指向該行的索引超出范圍例外: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;
}
}
uj5u.com熱心網友回復:
因為你在回圈和做
i--;
j--;
然后在某個時候你打電話 while(num1.charAt(-1) - '0' >= 0 && ...
快速的解決方案是測驗它i并且j比-1你的回圈更大。
while(i >= 0 && j >= 0 && num1.charAt(i) - '0' >= 0 && num2.charAt(j) - '0' >= 0) {
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/403805.html
標籤:
