计算两个字符串的减法运算

 1  /**
 2      * 两个大数相减,默认没有符号位,且都为正数
 3      *
 4      * @param a
 5      * @param b
 6      * @return
 7      */
 8     public static String bigDigitalSub(String a, String b) {
 9         //翻转字符串并转化成数组
10         char[] aArray = new StringBuilder(a).reverse().toString().toCharArray();
11         char[] bArray = new StringBuilder(b).reverse().toString().toCharArray();
12         int aLength = aArray.length;
13         int bLength = bArray.length;
14         //找到最大的位数,两个整数的差的位数小于等于两个整数中的最大位数
15         int maxLength = aLength > bLength ? aLength : bLength;
16         int[] result = new int[maxLength];
17         //判断结果符号
18         char sign = '+';
19         if (aLength < bLength) sign = '-';
20         else if (aLength == bLength) {
21             int i = maxLength - 1;
22             while (i > 0 && aArray[i] == bArray[i])
23                 i--;
24             if (aArray[i] < bArray[i])
25                 sign = '-';
26         }
27         //开始计算结果集
28         for (int i = 0; i < maxLength; i++) {
29             int aInt = i < aLength ? aArray[i] - '0' : 0;
30             int bInt = i < bLength ? bArray[i] - '0' : 0;
31             if (sign == '-') result[i] = bInt - aInt;
32             else result[i] = aInt - bInt;
33         }
34         //处理结果集,如果结果集中的某一位小于0,则向高位借位,然后将本位加10
35         for (int i = 0; i < maxLength - 1; i++) {
36             if (result[i] < 0) {
37                 result[i + 1] -= 1;
38                 result[i] += 10;
39             }
40         }
41 
42         //处理结果集,转化成真正结果
43         StringBuffer realResult = new StringBuffer();
44         if (sign == '-') realResult.append('-');
45         boolean isBeginning = true;
46         for (int i = maxLength - 1; i >= 0; i--) {
47             if (result[i] == 0 && isBeginning) continue;
48             else isBeginning = false;
49             realResult.append(result[i]);
50         }
51         if (realResult.toString().equals("")) realResult.append('0');
52         return realResult.toString();
53     }

 

posted @ 2017-10-30 12:30  daniel456  阅读(6640)  评论(0编辑  收藏  举报