试图添加大量数字

时间:2014-11-02 23:01:07

标签: java addition

我正在研究这个项目,并想知道是否有人可以帮助我。截至目前,我的程序适用于两个相同的数字整数,但当涉及两个不同的数字时,我的程序变得疯狂。看看我的代码:

这几乎是这个项目的最后一部分,我将完成。我还没学过[arr1> arr2?等等,等等。所以请不要提出类似的建议。我想要的是什么:

input: 500
input2: 50
output: 550

input: 50
input2: 500
output: 550

测试1:

input: 500
input2: 50
output: 100

感谢您的帮助。

3 个答案:

答案 0 :(得分:0)

编辑相关性
我将解释出现了什么问题,您需要调整算法以使其正常工作。

你结束了= 1.你检查j结束,这意味着你的循环将只运行一次(在这种情况下)。 sum以3位数字开头,然后设置sum[0] = 0 + 0。 sum现在是[0,0,0]。然后在下一个for循环中,检查是否sum[2] == 0,如果它是增量sum [0],则不确定原因。我想你真的想继续'并继续检查零,直到第一个数字实际打印完毕,然后继续打印包括零的所有数字。

答案 1 :(得分:0)

简单,但可以说是便宜的解决方案,使数字长度相同。 (此处的示例代码假定为非负数)。

首先看一下哪个更长,然后交换,以便num1总是更长(如果它们不等于长度:

if(num2.length > num1.length) {
    //this is only true if num2 is longer than num1. We just swap them using a temp
    int[] temp;
    int[] temp = num1;
    num1 = num2;
    num2 = num1;
}

创建一个长度为最大数字的新数组(num_temp),然后将较短的数组复制到其中,然后用零填充。 (将所有内容包装在if(num1.length!= num2.length)中将是一个触摸清洁器。)

int[] num_temp = new int[num1.length];
for(int i=0; i < num_temp.length; i++) {
    if(i < num2.length) { 
        // if we are still within the actual number
        num_temp[i] = num2[i];
    } else {
        // we're beyond the actual number at this point, just pad with 0's
        num_temp[i] = 0;    
    }
}
num2 = num_temp; //swap padded number in place.

好的,现在你有两个数字,num1和num2是相同的长度(如果需要的话,num2在前面填充0&#39; s)。不知道他们是否完全修复了你的代码,但它基本上删除了数字长度与问题不同的情况。

答案 2 :(得分:0)

在编写代码和创建自己的reversechar2Integerpad函数时,原始问题已丢失。但是,如果我记得它在你的循环中,你试图删除前导空格。无论如何,这是我到目前为止所做的,它似乎完美无缺:

public static void  main(String[] args)
{
    Scanner sc = new Scanner(System.in);
    System.out.print("Input int1: ");
    char[] firstInteger = sc.nextLine().toCharArray();
    System.out.print("Input int2: ");   
    char[] secondInteger = sc.nextLine().toCharArray();

    int[] num1 = char2Integer(firstInteger);
    int[] num2 = char2Integer(secondInteger);

    sum2(reverse(num1), reverse(num2)); //different length, assumed num1 is bigger
}

public static void sum2(int[] num1, int[] num2)
{
    //int over = num1.length-num2.length;
    int[] sum = new int[num1.length+1];
    //The pad function pads the array with 0 so there are no out of range exceptions
    num1 = pad(num1, sum.length);
    num2 = pad(num2, sum.length);

    for (int i = 0;  i < num1.length; i++)
    {
        sum[i] = sum[i] + num1[i] + num2[i];

        //if an element exceeds a value of 10
        if (sum[i] >= 10)
        {
            sum[i] = sum[i]%10;
            sum[i+1]++;
        }
    }
    sum = reverse(sum);
    for (int i = 0; i < sum.length; i++)
        System.out.print(sum[i]);
}

这就是我为你编写的打击垫功能。

public static int[] pad(int[] toPad, int length)
{
    int[] returnArray = new int[length];
    int i;
    for (i = 0; i < toPad.length; i++)
        returnArray[i] = toPad[i];
    for (int j = i; j < returnArray.length; j++)
        returnArray[j] = 0;
    return returnArray;
}

它没有删除前导零,我会留给你。我现在不能完成所有的工作,是吗?