2019-02-27 大数相乘

接前文 大数运算

参考:https://blog.csdn.net/outsanding/article/details/79472376

大数相乘:

思想:将输入的字符串,转成char数组,转成int数组。采用分治思想,每一位的相乘。

公式:AB*CD  =  AC (BC+ AD) BD,然后   从后到前满十进位。

如:67*89 = 6*8(7*8 + 6*9)7*9  =48(110)63

从后到前满十进位 

63进6余3--->48(116)3

116进11余6--->59 (6)3

最终结果5963


实现过程

public String multiply(String num1, String num2) {  

     //把字符串转成char数组

     char chars1[] = num1.toCharArray();

     char chars2[] = num2.toCharArray();


     //声明存放结果和两个乘积的容器

     int result[] = new int[chars1.length + chars2.length];

     int n1[]= newint[chars1.length];

     int n2[]= newint[chars2.length];


     //把char转换成int数组。

     for (int i =0; i < chars1.length; i++){

        n1[i] = Integer.parseInt(String.valueOf(chars1[i]));

     }


     for (int j =0; j < chars2.length; j++){

        n2[j] =  Integer.parseInt(String.valueOf(chars2[j]));

     }


     //逐个相乘

     for (int i = 0; i < chars1.length; i++){

        for (int j = 0; j < chars2.length; j++) {

          result[i+j] += n1[i]  *  n2[j];

        }

     }


     //从后往前满十进位

     for (int i = result.length -1; i > 0; i--) {

        result[i-1] += result[i] / 10;

        result[i] = result[i] % 10;

     }


     //转成string并返回

     String resultStr = "";

     for (int i = 0; i < result.length - 1; i++) {

        resultStr += "" +result[i];

     }

     returnresultStr;

   }

---------------------

作者:illustriousness

来源:CSDN

原文:https://blog.csdn.net/outsanding/article/details/79472376

版权声明:本文为博主原创文章,转载请附上博文链接!

你可能感兴趣的:(2019-02-27 大数相乘)