洛谷 P1303 A*B Problem 题解 高精度 模拟 C/C++

  • 思路如下:

1.首先是当作字符串读入,然后逆序存储到整型数组中,便于模拟乘法
2. 两层for循环模拟竖式乘法
3.注意前导0和一些索引处理;结果数组ans[]中的索引也可以用i+j-1 表示

//P1303 A*B Problem
//#define LOCAL
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <algorithm>
#include <cctype>
#include <sstream>
#define inf 0x3f3f3f3f
#define eps 1e-6
using namespace std;
#define clr(x) memset(x,0,sizeof((x)))
const int maxn = 10000;
#define MAX(a,b,c) ((a)>(b)?((a)>(c)?(a):(c)):((b)>(c)?(b):(c)))
#define _max(a,b) ((a) > (b) ? (a) : (b))
#define _min(a,b) ((a) < (b) ? (a) : (b))
#define _for(a,b,c) for(int a = b;a<c;a++)

char a[maxn],b[maxn];
int c[maxn],d[maxn],ans[maxn];
int main()
{
    
    
#ifdef LOCAL 
	freopen("data.in","r",stdin);
	freopen("data.out","w",stdout);
#endif
	scanf("%s%s",a,b);
	int la = strlen(a),lb = strlen(b);
	//逆序存储
	for(int i = 0;i<la;i++) {
    
    
		c[i] = a[la-i-1]-'0';
	}
	for(int j = 0;j<lb;j++) {
    
    
		d[j] = b[lb-j-1] - '0';
	}

	int carry,index,tmp=0;
	for(int i = 0;i<la;i++) {
    
    
		index = tmp;
		carry = 0;//进位
		for(int j = 0;j<lb;j++) {
    
    
			ans[index] += c[i]*d[j]+carry;
			carry = ans[index]/10;
			ans[index++] %=10;
		}
		if(carry)ans[index++] = carry;
		tmp++;
	}
	int k;
	for(k = index-1;k>=0;k--) {
    
    
		if(ans[k])break;//找到前导0的位置
	}
	k = _max(k,0);//结果为0时,k应该等于0
	for(int i = k;i>=0;i--)cout<<ans[i];
	
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Jason__Jie/article/details/114105899