【算法练习】高精度计算 百练poj 2389:Bull Math

本文介绍了一种不使用特殊库函数的大整数乘法算法,通过倒序存储和逐位相乘的方法,实现了两个大整数的精确相乘,并提供了完整的AC代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:http://bailian.openjudge.cn/practice/2389

2389:Bull Math

总时间限制: 

1000ms

 

内存限制: 

65536kB

描述

Bulls are so much better at math than the cows. They can multiply huge integers together and get perfectly precise answers ... or so they say. Farmer John wonders if their answers are correct. Help him check the bulls' answers. Read in two positive integers (no more than 40 digits each) and compute their product. Output it as a normal number (with no extra leading zeros).

FJ asks that you do this yourself; don't use a special library function for the multiplication.

输入

* Lines 1..2: Each line contains a single decimal number.

输出

* Line 1: The exact product of the two input lines

样例输入

11111111111111
1111111111

样例输出

12345679011110987654321

题意:大整数乘法

AC代码:

注意就是倒序,然后从1开始存,每一位相乘

//倒序保存
//从1开始
for(int i=0;i<len1;i++){
    t1[len1-i]=str1[i]-'0';
}
for(int i=1;i<=len1;i++){
    int x=0;  //进位
    for(int j=1;j<=len2;j++){
        a[i+j-1]+=x+t1[i]*t2[j]; //原来位置有数
        x=a[i+j-1]/10; //进位计算
        a[i+j-1]=a[i+j-1]%10;
    }
    a[i+len2]=x;
}

 

#include<iostream>
#include<string.h>
using namespace std;
//大整数乘法
char str1[100],str2[100];
int t1[100],t2[100],a[100];
int main(){
    cin>>str1>>str2;
    int len1=strlen(str1);
    int len2=strlen(str2);
    //倒序保存
    //从1开始
    for(int i=0;i<len1;i++){
        t1[len1-i]=str1[i]-'0';
    }

    for(int i=0;i<len2;i++){
        t2[len2-i]=str2[i]-'0';
    }

    for(int i=1;i<=len1;i++){
        int x=0;  //进位
        for(int j=1;j<=len2;j++){
            a[i+j-1]+=x+t1[i]*t2[j]; //原来位置有数
            x=a[i+j-1]/10; //进位计算
            a[i+j-1]=a[i+j-1]%10;
        }
        a[i+len2]=x;
    }
    //乘法位数相加
    int lena=len1+len2;
    //去掉前导0  存的时候在后面
    while(a[lena]==0 && lena>1) lena--;
    for(int i=lena;i>=1;i--){
        cout<<a[i];
    }
    cout<<endl;

    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值