两个大整数乘法


代码演示

#include <stdio.h>
#include <string.h>
//一般方法

char s1[1005], s2[1005];
int n1[1005], n2[1005], ans[2005];

int main() {
    scanf("%s", s1);
    scanf("%s", s2);
    n1[0] = strlen(s1), n2[0] = strlen(s2);
    
    for (int i = 0, j = n1[0]; s1[i] && j; j--, i++) n1[j] = s1[i] - '0';//倒序存储 
    for (int i = 0, j = n2[0]; s2[i] && j; j--, i++) n2[j] = s2[i] - '0';//倒序存储 
    ans[0] = n1[0] + n2[0] - 1; //估计答案最短长度
     
    for (int i = 1; i <= n1[0]; i++) { // 乘法 
        for (int j = 1; j <= n2[0]; j++) {
            ans[i + j - 1] += n1[i] * n2[j];
        }
    }
    
    for (int i = 1; i <= ans[0]; i++) { //进位 
        if (ans[i] > 9) {
            ans[i + 1] += ans[i] / 10;
            ans[i] %= 10;
            if (i == ans[0]) {
                ++ans[0];
            }
        }
    }
    
    for (int i = ans[0]; i; i--) printf("%d", ans[i]); //答案倒序输出 
    
    return 0;
}

习题

海贼oj471

文章作者: Axieyun
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Axieyun !
评论
评论
  目录