A * B Problem
Input
Each line contain two integers A and B. Procss to end of file.(EOF)
Output
For each case, Please output the value of A multiply B
Sample Input 1
3 2
1 5
Sample Output 1
6
5
思路:
用小学数学的乘法的方法,代码如下:
#include<stdio.h>
#include<string.h>
int main()
{
char arr1[101],arr2[101];
int a[101],b[101],c[201],i,j,k;
while(scanf("%s%s",&arr1,&arr2)!=EOF)
{
int n=strlen(arr1);
int m=strlen(arr2);
k=n+m;//俩数相乘小于俩数的位数相加
memset(c,0,sizeof(c));//数组初始化
for(i=0;i<n;i++)a[i]=arr1[n-1-i]-'0';//数倒序储存到另一个数组
for(i=0;i<m;i++)b[i]=arr2[m-1-i]-'0';
for(i=0; i<n; i++)
for(j=0; j<m; j++)
c[i+j]+=a[i]*b[j],c[i+j+1]+=c[i+j]/10,c[i+j]=c[i+j]%10;//相乘和进位
i=k;
while(c[i]==0&&i>0)i--;//去掉前导
for(;i>=0;i--)printf("%d",c[i]);
printf("\n");
}
return 0;
}
用vector的方法:
#include<iostream>
#include<vector>
using namespace std;
const int N = 1e6 + 10;
string s1, s2;
vector<int> a;
int b;
vector<int> mul(vector<int> a, int b)
{
vector<int> c;
int t = 0;
for(int i = 0; i < s1.size(); i++){
t += a[i] * b;
c.push_back(t % 10);
t /= 10;
}
while(t){
c.push_back(t % 10);
t /= 10;
}
return c;
}
int main()
{
cin >> s1 >> b;
for(int i = s1.size() - 1; i >= 0; i--)
a.push_back(s1[i] - '0');
a = mul(a, b);
for(int i = a.size() - 1; i >= 0; i--)
cout << a[i];
cout << endl;
return 0;
}