所谓大数相乘(Multiplication algorithm),就是指数字比较大,相乘的结果超出了基本类型的表示范围,所以这样的数不能够直接做乘法运算。
import java.util.Arrays;
import java.util.Stack;
/**
* 大数相乘
*/
public class BigNumberMutiply {
// 反转字符串
private String reverse(String s) {
Stack stack = new Stack();
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
stack.push(s.charAt(i));
}
while (!stack.isEmpty()) {
buffer.append(String.valueOf(stack.pop()));
}
return buffer.toString();
}
// 计算乘积
private void mutiply(String factor1, String factor2) {
factor1 = reverse(factor1);
factor2 = reverse(factor2);
int len1 = factor1.length();
int len2 = factor2.length();
// 保存结果的数组长度
int size = len1 + len2 + 3;
int[] res = new int[size];
// 结果
String result = "";
// 逐位相乘
for (int i = 0; i < len1; i++) {
for (int j = 0; j < len2; j++) {
res[i + j] += (Integer.parseInt(String.valueOf(factor1.charAt(i))))
* (Integer.parseInt(String.valueOf(factor2.charAt(j))));
}
}
// 进位处理
int m = 0;
while (m < size) {
int tmp = res[m] / 10;
res[m] = res[m] % 10;
if (tmp > 0) {
res[m + 1] += tmp;
}
m++;
}
// 找到最高位
m = size - 1;
while (res[m] <= 0) {
m--;
}
// 打印结果
while (m >= 0) {
result += res[m];
m--;
}
System.out.println("结果:" + result);
}
public static void main(String[] args) {
BigNumberMutiply mutiply = new BigNumberMutiply();
String factor1 = "12723169871651635965371";
String factor2 = "9867354656235626523526235665373";
System.out.println("乘数:" + factor1 + "\n" + "乘数:" + factor2);
mutiply.mutiply(factor1, factor2);
}
}
网友评论