【问题标题】:Adding integer strings: Index out of bounds exception for looping添加整数字符串:循环的索引超出范围异常
【发布时间】: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


【解决方案1】:

因为你在循环和做

i--;
j--;

那么在某些时候你会打电话给while(num1.charAt(-1) - '0' &gt;= 0 &amp;&amp; ...

快速解决方案是测试循环中的i 和j 是否大于-1。

while(i >= 0 && j >= 0 && num1.charAt(i) - '0' >= 0 && num2.charAt(j) - '0' >= 0) {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-16
    • 1970-01-01
    相关资源
    最近更新 更多