乘法
写来玩玩,任意两个整数相乘
#include<stdio.h>
#include<string.h>
void rev(char*a,int n){
int temp;
for (int i = 0; i < (n / 2); i++)
{
temp = *(a+i);
*(a+i) = *(a + n - i - 1);
*(a + n - i - 1) = temp;
}
}
char * multiply(char * num1, char * num2)
{
rev(num1,strlen(num1));
rev(num2,strlen(num2));
char mul[50000];
for(int i=0;i<50000;i++)
{
mul[i] = '0';
}
int k;
for(int i=0;i<strlen(num1);i++)
{
k = i;
for(int j=0;j<strlen(num2);j++)
{
if((num2[j]-'0')*(num1[i]-'0')>=10)
{
if((mul[k]-'0')+(num2[j]-'0')*(num1[i]-'0')%10>=10)
{
mul[k+1] = mul[k+1] + 1;
mul[k] = (mul[k]-'0')+(num2[j]-'0')*(num1[i]-'0')%10-10+'0';
}
else mul[k] = (mul[k]-'0')+(num2[j]-'0')*(num1[i]-'0')%10+'0';
mul[k+1] = (mul[k+1]-'0')+(num2[j]-'0')*(num1[i]-'0')/10+'0';
}
else
{
if((mul[k]-'0')+(num2[j]-'0')*(num1[i]-'0')>=10)
{
mul[k+1] = mul[k+1] + 1;
mul[k] = (mul[k]-'0')+(num2[j]-'0')*(num1[i]-'0')-10+'0';
}
else mul[k] = (mul[k]-'0')+(num2[j]-'0')*(num1[i]-'0')+'0';
}
k++;
}
}
if(mul[k]!='0')
{
mul[k+1] = '\0';
rev(mul,k+1);
}
else
{
mul[k] = '\0';
rev(mul,k);
}
return mul;
}
int main()
{
char num1[200];
char num2[200];
gets(num1);
gets(num2);
printf("%s",multiply(num1,num2));
}