乘法运算可以分拆为两步:第一步,是将乘数与被乘数逐位相乘;第二步,将逐位相乘得到的结果,对应相加起来。这有点类似小学数学中,计算乘法时通常采用的“竖式运算”。
package binary.search;
import java.util.Scanner;
public class Demo2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str1 = sc.next();
String str2 = sc.next();
int[] num1 = new int[str1.length()];
int[] num2 = new int[str2.length()];
//把字符串转换成int数组,需要注意:为了操作方便,要进行倒序操作
for (int i = 0; i < str1.length(); i++) {
num1[str1.length() - 1 - i] = str1.charAt(i) - '0';
}
for (int i = 0; i < str2.length(); i++) {
num2[str2.length() - 1 - i] = str2.charAt(i) - '0';
}
int[] result = multiply(num1, num2);
for (int i = result.length - 1; i >= 0; i--) {
if(i==result.length - 1)
if(result[i]==0)
continue;
System.out.print(result[i]);
}
sc.close();
}
public static int[] multiply(int[] num1, int[] num2) {
int lengthOfNum1 = num1.length;
int lengthOfNum2 = num2.length;
//如果num1和num2的长度分别为n1,n2,那么它们相乘的结果位数为n1+n2-1到n1+n2
int[] result = new int[lengthOfNum1 + lengthOfNum2];
//num[i]*num2[j]的结果存在result[i+j]上,最后再处理进制问题
for (int i = 0; i < lengthOfNum1; i++) {
for (int j = 0; j < lengthOfNum2; j++) {
result[i + j] += num1[i] * num2[j];
}
}
// 处理进制问题
for (int i = 0; i < lengthOfNum1 + lengthOfNum2 - 1; i++) {
if (result[i] >= 10) {
result[i + 1] += result[i] / 10;
result[i] = result[i] % 10;
}
}
return result;
}
}