首页 > 技术文章 > C#实现大数相加

AaronBlogs 2017-05-14 19:37 原文

在C#中,我们经常需要表示整数。但是,c#的基本数据类型中,最大的long也只能表示-9,223,372,036,854,775,808 到 9,223,372,036,854,775,807之间的数。

如果我们需要表示更大的数,就需要用到一定的算法来完成。

这次,我给大家分享一下C##的大数运算之加法。

代码只考虑了正数的整数加法。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace ConsoleApplication1
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             Console.WriteLine("请输入第一个加数");
14             string oneNum = Console.ReadLine();
15             Console.WriteLine("请输入第二个加数");
16             string twoNum = Console.ReadLine();
17 
18             string result = TwoBigNumAdd(oneNum, twoNum);
19             Console.WriteLine(result);
20         }
21 
22         static string TwoBigNumAdd(string a, string b)
23         {
24             int k = 0;
25             List<int> array = new List<int>();
26             List<int> one = new List<int>();
27             List<int> two = new List<int>();
28 
29             //将两个数处理成相同长度的字符串,短的小的数字前面补0
30             for (int i = 0; i < (a.Length > b.Length ? a.Length : b.Length); i++)
31             {
32                 if (i >= a.Length)
33                     one.Insert(i - a.Length, 0);
34                 else
35                     one.Add(int.Parse(a[i].ToString()));
36                 if (i >= b.Length)
37                     two.Insert(i - b.Length, 0);
38                 else
39                     two.Add(int.Parse(b[i].ToString()));
40             }
41 
42             //array集合用于存储相加的和,所以长度最大也只会比最大的数长度长1,刚开始全部存0
43             for (int i = 0; i <= (a.Length > b.Length ? a.Length : b.Length); i++)
44             {
45                 array.Add(0);
46             }
47 
48             //从低位往高位每位开始相加,如果相加 >=10 则进1取余
49             for (int i = (a.Length > b.Length ? a.Length : b.Length) - 1; i >= 0; i--)
50             {
51                 array[i + 1] += (one[i] + two[i]) % 10;
52                 k = (one[i] + two[i]) / 10;
53 
54                 array[i] += k;
55             }
56 
57             //如果首位为0,则移除
58             if (array[0] == 0)
59             {
60                 array.RemoveAt(0);
61             }
62 
63             //将集合转换成字符串返回
64             StringBuilder result = new StringBuilder();
65             for (int i = 0; i < array.Count; i++)
66             {
67                 result.Append(array[i]);
68             }
69             return result.ToString();
70         }
71     }
72 }

 

推荐阅读