#include<string>
using namespace std;
void multiply(char a[],char b[],char result[])
{
int i,j,k,index,carry,mul,len1,len2;
if(strcmp(a,"0")==0 || strcmp(b,"0")==0)
{
strcpy(result,"0");
return;
}
len1=strlen(a); len2=strlen(b);
j = len1+len2;
memset(result,'0',sizeof(result));
index=-1;
for(i=len2-1;i>=0;i--)
{
index++; carry=0;
for(j=len1-1,k=index;j>=0;j--,k++)
{
mul = (a[j] - '0')*(b[i] - '0') + (result[k] - '0') + carry;
carry = mul/10;
result[k] = (mul%10) + '0';
}
result[k] = (carry%10) + '0';
}
if(carry !=0 )
k++;
result[k]='\0';
reverse(&result[0],&result[k]);
return;
}
int main()
{
char a[300],b[300],result[600];
while(scanf( "%s %s",a,b)==2)
{
multiply(a,b,result);
printf("%s\n",result);
}
return 0;
}
#################################################################################
#include <stdio.h>
#include <string.h>
#define n 500
char res[2*n] ;
void Multiplication( char ch1[], char ch2[] )
{
char ch3[n], sign1, sign2 ;
int len1, len2, i, j, k, l, temp, carry, sum, l1, l2;
sign1 = ch1[0];
sign2 = ch2[0];
if( sign1!='-' && sign1!='+' ) len1 = strlen(ch1);
else{
strcpy( ch1, &ch1[1] );
len1 = strlen( ch1 );
}
if( sign2!='-' && sign2!='+' ) len2 = strlen( ch2 );
else
{
strcpy( ch2, &ch2[1] );
len2 = strlen( ch2 );
}
for(l1=0;ch1[l1]=='0';l1++);
for(l2=0;ch2[l2]=='0';l2++);
if( l1==len1 || l2==len2 )
{
res[0] = '0'; res[1] = '\0';
return ;
}
for(i=0;i<n;i++)
ch3[i]=0;
for(l=0,i=len2-1;i>=l2;i--)
{
for(k=l,carry=0,j=len1-1;j>=l1;j--)
{
temp=(ch1[j]-48)*(ch2[i]-48)+carry;
if(ch3[k]!=0)
temp+=ch3[k]-48;
sum=temp%10;
carry=temp/10;
ch3[k]=sum+48;
k++;
}
if(carry>0)
ch3[k++]=carry+48;
ch3[k]='\0';
l++;
}
i=strlen(ch3);
j = 0 ;
if( ( sign1=='-' && sign2!='-' ) || ( sign2=='-' && sign1!='-') )
res[j++] = '-' ;
while(--i>=0) res[j++] = ch3[i];
res[j] = '\0';
}
int main()
{
char ch1[n], ch2[n] ;
while(scanf(" %s %s",ch1,ch2)==2)
{
Multiplication( ch1, ch2 );
printf("%s\n",res);
}
return 0;
}
No comments:
Post a Comment