Bull Math
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 14972 | Accepted: 7695 |
Description
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.
FJ asks that you do this yourself; don't use a special library function for the multiplication.
Input
* Lines 1..2: Each line contains a single decimal number.
Output
* Line 1: The exact product of the two input lines
Sample Input
11111111111111 1111111111
Sample Output
12345679011110987654321
题意:输入两个大数,输出它们相乘的结果。
代码:
#include <iostream> #include <cstdio> #include <cstring> #define MAX 10000 using namespace std; typedef struct bignum //定义大数类型 { bignum(){memset(arr,0,sizeof(arr));length=0;} //初始化成员变量 int arr[MAX*2]; int length; }Bignum; char s[MAX]; char t[MAX]; Bignum atoi(char *s) //字符串转换为大数类型 { Bignum res; int slen=strlen(s); for(int k=slen-1;k>=0;k--) { res.arr[k]=s[k]-'0'; } res.length=slen; return res; } //大数相乘 Bignum quickmul(Bignum a,Bignum b) { Bignum res; //存放结果 for(int i=0;i<a.length;i++) { for(int j=0;j<b.length;j++) { res.arr[i+j+1]+=a.arr[i]*b.arr[j]; //将a,b按位相乘 } } res.length=a.length+b.length; //记得长度要更新 //处理进位 int temp=0; //temp表示进位 for(int i=res.length-1;i>=0;i--) //从后往前处理 { int sum=res.arr[i]+temp; res.arr[i]=sum%10; temp=sum/10; } if(temp) //如果处理到最高位依然有进位,(左->右==>>高位->低位) res.arr[0]=temp; if(res.arr[0]==0) //如果res.arr[0]为0,把这个0去掉 { for(int i=0;i<res.length-1;i++) res.arr[i]=res.arr[i+1]; res.length--; } return res; } //输出大数 void print(Bignum b) { for(int i=0;i<b.length;i++) cout<<b.arr[i]; cout<<endl; } int main() { while(cin>>s>>t) { Bignum a=atoi(s); Bignum b=atoi(t); print(quickmul(a,b)); } return 0; }