描述
实现大数乘法,输入是两个字符串如
n1 = '340282366920938463463374607431768211456'
n2 = '340282366920938463463374607431768211456'
输出
'115792089237316195423570985008687907853269984665640564039457584007913129639936'
要求:不能使用对大数相乘有内建支持的语言;需要包含对输入字符串的合法性校验
输入描述:
一行,两个非负整数n1,n2,保证|n1|+|n2|<10000,其中|n|是n作为字符串的长度
输出描述:
输出n1*n2的结果
示例1
输入:
340282366920938463463374607431768211456 340282366920938463463374607431768211456
输出:
115792089237316195423570985008687907853269984665640564039457584007913129639936
import java.util.Scanner;
public class Main {
public static void main(String[] argc) {
Scanner scaner = new Scanner(System.in);
String n1 = scaner.next();
String n2 = scaner.next();
/*String n1 = "1234567";
String n2 = "123";*/
int[] n1Num = new int[n1.length()];
int[] n2Num = new int[n2.length()];
for(int i=0; i<n1.length(); i++) {
n1Num[i] = n1.charAt(i) - '0';
}
for(int j=0; j<n2.length(); j++) {
n2Num[j] = n2.charAt(j) - '0';
}
int[] result = new int[n1.length() + n2.length()];
for(int i=0; i<n1.length(); i++) {
for(int j=0; j<n2.length(); j++) {
result[i+j+1] += n1Num[i] * n2Num[j];//注意这里是+=
}
}
for(int k=result.length-1;k>0;k--) {
if(result[k] >= 10) {
result[k-1] += (result[k] / 10);
result[k] = result[k] % 10;
}
}
boolean start = false;
for(int k=0;k<result.length;k++) {
if(result[k]>0 || start) {
System.out.print(result[k]);
start = true;
}
}
}
}