Caterl Java寒假基础练习题(一) 循环相加

题目一:

    求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字。

    例如2+22+222+2222+22222(此时共有5个数相加),几个数相加由键盘控制。

分析:

  对于少量的简单数据,此题很简单就可以实现。但是如果给出的数据较大,比如超过 int 的范围就无法计算出正确结果。因此,需要实现高精度的加法。

  用两个分别存放加数、被加数和结果用数组模拟加法的过程。

代码:

  

 1 import java.util.Scanner;
 2 
 3 public class plus {
 4     public static void main(String[] args) {
 5         
 6         final int LEN = 1000;
 7         int[] number = new int[LEN];
 8         
 9         //重复的数字
10         System.out.println("请输入要重复的数字:");
11         Scanner sc_in = new Scanner(System.in);
12         int in = sc_in.nextInt();
13         
14         //重复次数
15         System.out.println("请输入要重复的次数:");
16         Scanner sc_time = new Scanner(System.in);
17         int time = sc_time.nextInt();
18         
19         //将各位数相加
20         for (int i = 0, j = time; i < time; i++) {
21             number[i] = j*in;
22             --j;
23         }
24         
25         //对数组处理
26         calc(number);
27         
28         //输出结果
29         for (int i = number.length-1; i >= 0; --i) {
30             if (number[i] != 0) {
31                 for (int j = i; j >= 0; j--) {
32                     System.out.print(number[j]);
33                 }
34                 break;
35             }
36             if(i == 0){
37                 System.out.println(0);
38             }
39         }
40     }
41     
42     //对数据处理
43     public static void calc(int[] number){
44         for (int i = 0; i < number.length; i++) {
45             if (number[i] > 9) {
46                 for(int j = 0; j < number.length-1; j++) {
47                     number[j+1] += number[j]/10;
48                     number[j] %= 10;
49                 }
50                 calc(number);
51             }
52         }
53     }
54     
55 }

运行结果:

原文地址:https://www.cnblogs.com/CocoonFan/p/2923266.html