求两个很大的数相乘,如:123456789123456789*123456789123456789
package com.ldq;
/*
* 两个很大的数相乘
* */
public class Multi {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String a = "123456789123456789123456789123456789123456789123456789";
String b = "123456789123456789123456789123456789123456789123456789";
int m = a.length();
int n = a.length();
int aa[] = new int[100];
int bb[] = new int[100];
int cc[] = new int[500];
for (int i = 0; i < a.length(); i++) {
aa[i] = Integer.parseInt(a.substring(a.length() - i - 1, a.length()
- i));
bb[i] = Integer.parseInt(b.substring(b.length() - i - 1, b.length()
- i));
}
int t = 0;
for (int j = 0; j < n; j++) {
for (int i = 0; i < m; i++) {
t = cc[i + j] + aa[i] * bb[j];
cc[i + j] = t % 10;
cc[i + j + 1] += t / 10;
if (cc[i + j + 1] > 10) {
cc[i + j + 1] %= 10;
cc[i + j + 2]++;
}
}
}
for (int i = 200; i >= 0; i--) {
System.out.print(cc[i]);
}
}
}
主要思路就是用两个整型数组保存相乘的数,用两个 for 循环模拟乘法过程就 OK 了。也不难。