呃,啥都不说了,哥将近半个月没写代码,先前代码写的也少,一下脑袋就闷了.不过好歹底子还在.总算花了点时间搞出来了.
1: public class BigNumberAdd {
2:
3: /**
4: * @param args
5: */
6: public static void main(String[] args) {
7: String add = "9";
8: String added = "1";
9:
10: System.out.println(bigNumadd(add, added));
11:
12: }
13:
14: /**
15: * 如果出现加数或者被加数为负数,则算法会失效
16: * @param add 加数
17: * @param added 被加数
18: * @return 相加结果
19: *
20: */
21: public static String bigNumadd(String add, String added) {
22: int addLen = add.length();
23: int addedLen = added.length();
24: int carray = 0;
25: StringBuffer result = new StringBuffer();
26: int i = addLen - 1;
27: int j = addedLen - 1;
28: int a = 0;
29: int b = 0;
30: int r = 0;
31: for (; i >= 0 && j >= 0; i--, j--) {
32: a = Integer.parseInt(add.substring(i, i + 1));
33: b = Integer.parseInt(added.substring(j, j + 1));
34: r = a + b + carray;
35: if (r < 10) {
36: carray = 0;
37: result.insert(0, r);
38: } else {
39: carray = 1;
40: result.insert(0, r % 10);
41: }
42: }
43: if (addLen > addedLen) {
44: for (; i >= 0; i--) {
45: a = Integer.parseInt(add.substring(i, i + 1));
46: r = a + carray;
47: if (r < 10) {
48: carray = 0;
49: result.insert(0, r);
50: } else {
51: carray = 1;
52: result.insert(0, r % 10);
53: }
54: }
55: if (carray != 0) {
56: result.insert(0, 1);
57: }
58: } else if (addedLen > addLen) {
59: for (; j >= 0; j--) {
60: b = Integer.parseInt(added.substring(j, j + 1));
61: r = b + carray;
62: if (r < 10) {
63: carray = 0;
64: result.insert(0, r);
65: } else {
66: carray = 1;
67: result.insert(0, r % 10);
68: }
69: }
70: if (carray != 0) {
71: result.insert(0, 1);
72: }
73: } else {
74: if (carray != 0) {
75: result.insert(0, 1);
76: }
77: }
78: return result.toString();
79: }
80:
81: }