1

当我运行我的程序时,我不断收到这些错误,有人能发现错误吗?我没有使用递归的经验,我可能搞砸了基本情况。我的测试由两个长度相同的数字组成,我的目标是在不使用内置类的情况下将两个大数字相乘。add 方法只接受两个数字字符串并将它们相加,我检查了一下,无论数字有多大,它都可以工作。

错误 NumberFormatException:对于输入字符串:“” Integer.parseInt(Integer.java:592)

public static String mu (String value1, String value2){

    int length1 = value1.length();
    int length2 = value2.length();

    //If one value has more digits than the other, add zeroes to the front...



    int temp1;
    int temp2;
    int multiply;

    if (length1==1 || length2 ==1){
        temp1 = Integer.parseInt(value1);
        temp2 = Integer.parseInt(value2);
        multiply = temp1*temp2;
        return multiply +"" ;
    }else if (length1 ==0 || length2 ==0){
        return "";
    }



        int firstHalf = length1/2;
        int secondHalf = length1 - firstHalf;

        String value1First = value1.substring(0, firstHalf);
        String value1Second = value1.substring(firstHalf, secondHalf);


        String value2First = value2.substring(0, firstHalf);
        String value2Second = value2.substring(firstHalf, secondHalf);

        String ac = mu (value1First, value2First);
        String ad = mu (value1First, value2Second);
        String bc = mu(value1Second, value2First);
        String bd = mu(value1Second, value2Second);

        String zeroesToAdd= null;
        String zeroesToAdd2 = null;
        for (int i=0; i<length1; i++){
            zeroesToAdd = "0"+ zeroesToAdd;
        }
        for (int i=0; i<length1/2; i++){
            zeroesToAdd2 = "0"+ zeroesToAdd2;
        }

        String firstPart = ac + zeroesToAdd;
        String secondPart = (add(ad,bc))+zeroesToAdd2;
        String thirdPart = bd;

        String add1 = add(firstPart, secondPart);
        String add2;




        return add(add1, thirdPart);
    }
4

1 回答 1

2

错误 NumberFormatException:对于输入字符串:“” Integer.parseInt(Integer.java:592)

是代码造成的

Integer.parseInt(value1)  or
Integer.parseInt(value2)

您可能想尝试为 str 长度 (1,1) (1,0) (0,1) (0,0) 的组合添加更多案例。以下代码可能会有所帮助!

if (length1==1 && length2 ==1){
    temp1 = Integer.parseInt(value1);
    temp2 = Integer.parseInt(value2);
    multiply = temp1*temp2;
    return multiply +"" ;
}else if (length1 ==0 && length2 ==0){
    return "";
}
else if (length1 ==0 && length2 ==1){
    return value2;
}
else if (length1 ==1 && length2 ==0){
    return value1;
}

希望能帮助到你!

于 2017-07-03T05:25:31.233 回答