1207: 大整数的乘法
题目描述
输入
输出
样例输入
12345678900 98765432100
样例输出
1219326311126352690000
分析(Java):
使用Java的BigInteger类来解决
核心代码:
1 a = sc.nextBigInteger(); 2 b = sc.nextBigInteger(); 3 System.out.println(a.nultiplt(b));
Java代码实现(AC):
1 import java.math.BigInteger; 2 import java.util.Scanner; 3 4 5 public class Main{ 6 public static void main(String args[]) { 7 Scanner sc = new Scanner(System.in); 8 BigInteger a, b; 9 a = sc.nextBigInteger(); 10 b = sc.nextBigInteger(); 11 System.out.println(a.multiply(b)); 12 } 13 }
分析(C/C++):
Ⅰ、用C/C++进行乘法运算,就是模拟乘法运算的整个过程;
Ⅱ、要注意两点:
①、进位的处理
②、每一层运算要做到最低位的对齐原则
步骤:
①、将字符串的输入转化为对应的整型数组
②、遍历一个整型数组的每一个数与另一个整型数组所有的数相乘
③、PS,注意:进位、对齐
核心代码:
1 for(int i = 0; i < len1; ++ i) 2 { 3 int b = 0; 4 for(int j = 0; j < len2 || b; ++ j) 5 { 6 int t = i1[i]*i2[j] + ans[i+j] + b; 7 ans[i+j] = t%10; 8 b = t/10; 9 len = max(len, i+j); // len保存最终位数 10 } 11 }
C/C++代码实现(AC):
1 #include <iostream> 2 #include <algorithm> 3 #include <cstring> 4 #include <cstdio> 5 #include <cmath> 6 #include <stack> 7 #include <map> 8 #include <queue> 9 10 using namespace std; 11 12 int main() 13 { 14 char s1[205], s2[205]; 15 int len1, len2; 16 scanf("%s%s", s1, s2); 17 len1 = strlen(s1), len2 = strlen(s2); 18 19 int i1[205] = {0}, i2[205] = {0}, ans[1000] = {0}, len = 0; 20 for(int i = 0; i < len1; ++ i) 21 i1[i] = s1[len1 - 1 - i] - '0'; 22 for(int i = 0; i < len2; ++ i) 23 i2[i] = s2[len2 - 1 - i] - '0'; 24 25 for(int i = 0; i < len1; ++ i) 26 { 27 int b = 0; 28 for(int j = 0; j < len2 || b; ++ j) 29 { 30 int t = ans[i + j] + i1[i]*i2[j] + b; 31 ans[i + j] = t%10; 32 b = t/10; 33 len = max(len, j + i); 34 } 35 } 36 for(int i = len; i >= 0; -- i) 37 printf("%d", ans[i]); 38 printf("\n"); 39 return 0; 40 }