# 两个大数相加比较符合自然运算的算法

1public static string MaxNumAdd(string num1, string num2)
2        {
3            //初始设置进位为0
4            int carry = 0;
5            int length1 = num1.Length;
6            int length2 = num2.Length;
7            Stack<int> stack1 = new Stack<int>(length1);
8            Stack<int> stack2 = new Stack<int>(length2);
9            int max = length1;
10            if (max < length2)
11            {
12                max = length2;
13            }

14            //用于存放结果
15            Stack<int> stack3 = new Stack<int>(max + 1);
16            int size = max - length1;
17            while (size > 0)
18            {
19                stack1.Push(0);
20                size--;
21            }

22            size = max - length2;
23            while (size > 0)
24            {
25                stack2.Push(0);
26                size--;
27            }

28            for (int i = 0; i < length1; i++)
29            {
30
31                int num = Convert.ToInt32(num1[i].ToString());
32                stack1.Push(num);
33            }

34            for (int i = 0; i < length2; i++)
35            {
36
37                int num = Convert.ToInt32(num2[i].ToString());
38                stack2.Push(num);
39            }

40            //临时施计算结果
41            int tempResult = 0;
42            for (int i = 0; i < max; i++)
43            {
44                int n1 = stack1.Pop();
45                int n2 = stack2.Pop();
46                tempResult = n1 + n2 + carry;
47                stack3.Push(tempResult);
48                if (tempResult > 9)
49                {
50                    carry = 1;
51                }

52                else
53                {
54                    carry = 0;
55                }

56            }

57            stack3.Push(carry);
58            StringBuilder sb = new StringBuilder();
59            while (stack3.Count > 0)
60            {
61                sb.Append(stack3.Pop().ToString());
62            }

63            return sb.ToString().TrimStart('0');
64        }

65    }
posted @ 2006-10-22 02:06  Robin Zhang  阅读(3599)  评论(6编辑  收藏