首页 > 代码库 > 另类乘法
另类乘法
另类乘法
- 描述
Bessie is tired of multiplying pairs of numbers the usual way, so she invented her own style of multiplication. In her style, A*B is equal to the sum of all possible pairwise products between the digits of A and B. For example, the product 123*45 is equal to 1*4 + 1*5 + 2*4 + 2*5 + 3*4 + 3*5 = 54. Given two integers A and B (1 ≤ A, B ≤ 1,000,000,000), determine A*B in Bessie‘s style of multiplication.
- 输入
- The first Line of the input is a positive integer T,indicates the number of the test cases;
In every case,the input is in one line,contains two positive interger A,B - 输出
For every case,output the multiplication in Bessie‘s style.
- 样例输入
1 123 45
- 样例输出
54
方法一:字符串#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int t;
char a[11],b[11];
scanf("%d",&t);
while(t--)
{
int sum=0;
scanf("%s",a);
int l1=strlen(a);
scanf("%s",b);
int l2=strlen(b);
for(int i=0;i<l1;i++)
for(int j=0;j<l2;j++)
{
sum+=(a[i]-‘0‘)*(b[j]-‘0‘);
}
printf("%d\n",sum);
}
return 0;
}方法二:字符数组
#include<stdio.h>
int main()
{
int t,a,b;
int f[11],g[11];
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&a,&b);
int i=0,j=0,sum=0;
while(a)
{
f[i++]=a%10;
a=a/10;
}
while(b)
{
g[j++]=b%10;
b=b/10;
}
for(int l=0;l<i;l++)
for(int k=0;k<j;k++)
sum+=f[l]*g[k];
printf("%d\n",sum);
}
return 0;
}方法三:数字A和B分别将他们的各个位相加求和,再将两个和求积。
#include<stdio.h>
int main()
{
int t,a,b;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&a,&b);
int sum1=0,sum2=0;
while(a)
{
sum1+=a%10;
a/=10;
}
while(b)
{
sum2+=b%10;
b/=10;
}
int sum=sum1*sum2;
printf("%d\n",sum);
}
return 0;
}
另类乘法