使用Java中的数组添加两个10位数字

时间:2017-11-23 09:24:12

标签: java arrays algorithm

我想使用3个数组添加两个10位数字。我写了这些文字:

import java.util.*;

public class addition {
   public static void main(String[] args){
      Scanner enter = new Scanner(System.in);
      int[] arr1= new int[10];
      int[] arr2 = new int[10];
      int [] result = new int [11];

      System.out.print("Enter the first array: ");
      for(int i=0; i<10; i++)
      {
         arr1[i]=enter.nextInt();
      }
      System.out.print("Enter the second array: ");
      for(int i=0; i<10; i++)
      {
         arr2[i]=enter.nextInt();
      }

      for(int i=0; i<10; i++)
      {
         int b;
         int c;
         int a = arr1[9-i]+ arr2[9-i];
         if(a>9){
            b = a%10;
            c = a/10;
            result[9-i] = b;
            result[10-i] += c;
         }
         result[9-i]=a;
      }
      System.out.print("Result: "); 
      for(int i=10; i>=0; i--)
      {
         System.out.print(result[i]);
      }
   }
}

但该程序无法正常运行。结果不正确。

控制台:

Enter the first array: 8
6
9
5
3
9
9
1
4
2
Enter the second array: 8
5
3
8
0
0
3
1
6
6

结果:09103129414131216

我该怎么办?

2 个答案:

答案 0 :(得分:3)

有两件事需要解决:

  1. 您将阵列填充到前面,这使得输入符合直观。换句话说,这个循环:

    for(int i=0; i<10; i++) {
      arr1[i]=enter.nextInt();
    }
    

    应该成为:

    for(int i=9; i>=0; i--) {
      arr1[i]=enter.nextInt();
    }
    

    同样适用于arr2

  2. 检查进位的主if语句应该成为:

    if(a>9){
      b=a%10;
      c=a/10;
      result[9-i]=b;
      result[10-i]+=c;
    } else {
      result[9-i]=a;
    }
    
  3. 通过这些修补程序,您的代码可以正常运行。

    额外

    您可以更进一步,让您的进位计算更简单(仅因为我们只添加2位数。通过这样的假设,“加法器循环”变为:

    for(int i=0; i<10; i++) {
      int a = arr1[9-i] + arr2[9-i];
      if (a>9) {
        result[9-i] = a-10;
        result[10-i] += 1;
      } else {
        result[9-i] = a;
      }
    }
    

答案 1 :(得分:0)

在处理此类问题时,我们需要记住那里的随身携带。

要解决这个问题,我们应该从数组的右边开始添加到左边。就像我们在数学类中添加两个数字一样。

我们需要保持随身携带的轨道。