1. 程式人生 > >大整數乘法演算法

大整數乘法演算法

刷筆試題的時候遇到了一個大整數乘法的問題,做法就是模擬手工演算法,只要注意不能用long來儲存,而要使用string。其中還有一些細節需要注意,例如進位,正負號等。 程式碼如下:
public static void main(String[] args) {     Scanner in = new Scanner(System.in);     while (in.hasNext()) {         boolean s = true;
        String a = in.next();         String b = in.next();         if (a.charAt(0) == '-') {             a = a.substring(1, a.length());
            s = !s;         }         if (b.charAt(0) == '-') {             b = b.substring(1, b.length());
            s = !s;         }
        String[] resList = new String[1000];         for (int i = 0; i < 1000; i++) {             resList[i] = "0";         }         int plus = 0;         for (int i = b.length() - 1; i >= 0; i--) {             String tRes = "";             int now = Integer.parseInt(b.charAt(i) + "");             for (int j = a.length() - 1; j >= 0; j--) {                 int now2 = Integer.parseInt(a.charAt(j) + "");                 int tmp = now * now2 + plus;                 if (tmp < 10) {                     tRes = tRes + tmp;                     plus = 0;                 } else {                     tRes = tRes + (tmp % 10);                     plus = tmp / 10;                 }             }             if (plus != 0) {                 tRes = tRes + plus;                 plus = 0;             }             boolean plus2 = false;             for (int y = 0; y < tRes.length(); y++) {                 int tmp = Integer.parseInt(tRes.charAt(y) + "") + Integer.parseInt(resList[y + (b.length() - 1 - i)]) + (plus2 ? 1 : 0);                 if (tmp < 10) {                     resList[y + (b.length() - 1 - i)] = tmp + "";                     plus2 = false;                 } else {                     resList[y + (b.length() - 1 - i)] = tmp - 10 + "";                     plus2 = true;                 }             }             if (plus2) {                 resList[(b.length() - 1 - i) + tRes.length()] = Integer.parseInt(resList[(b.length() - 1 - i) + tRes.length()]) + "1";                 plus2 = false;             }
        }         boolean start = false;         System.out.print(s ? "" : "-");         for (int i = 999; i >= 0; i--) {             if (!start && resList[i].equals("0")) {                 continue;             }             if (!start && !resList[i].equals("0")) {                 start = true;                 System.out.print(resList[i]);             } else {                 System.out.print(resList[i]);             }         }     } }