codeup之特殊乘法

这篇博客介绍了如何编写算法来处理一种特殊的乘法运算,例如123*45=14+15+24+25+34+35。提供了四种不同的C语言解决方案,分别通过取位、字符串处理、字符数组转整型数组以及直接处理字符数组的方法来计算两个数的这种特殊乘积。每个解决方案都读取输入的两个数,然后通过两层循环计算所有可能的组合并累加结果。

Description

写个算法,对2个小于1000000000的输入,求结果。特殊乘法举例:123 * 45 = 14 +15 +24 +25 +34+35

Input

两个小于1000000000的数

Output

输入可能有多组数据,对于每一组数据,输出Input中的两个数按照题目要求的方法进行运算后得到的结果。

Sample Input Copy

24 65
42 66666
3 67

Sample Output Copy

66
180
39

solution(取出每位

#include <stdio.h>
int getNum(int a, int a1[]){
	int i = 0; 
	while(a){
		a1[i++] = a % 10;
		a /= 10;
	}
	return i;
}
int main(){
	int a, b, a1[10], b1[10], mul, temp;
	while(scanf("%d%d", &a, &b) != EOF){
		mul = 0;
		int n1 = getNum(a, a1), n2 = getNum(b, b1);
		for(int i = 0; i < n1; i++){
			for(int j = 0; j < n2; j++){
				mul += a1[i] * b1[j];
			}
		}
		printf("%d\n", mul);
	} 
	return 0;
}

solution(把输入作为字符串处理

#include <stdio.h>
int getNum(int a, int a1[]){
	int i = 0; 
	while(a){
		a1[i++] = a % 10;
		a /= 10;
	}
	return i;
}
int main(){
	int a, b, a1[10], b1[10], mul, temp;
	while(scanf("%d%d", &a, &b) != EOF){
		mul = 0;
		int n1 = getNum(a, a1), n2 = getNum(b, b1);
		for(int i = 0; i < n1; i++){
			for(int j = 0; j < n2; j++){
				mul += a1[i] * b1[j];
			}
		}
		printf("%d\n", mul);
	} 
	return 0;
}

solution3(字符数组转整型数组

#include <stdio.h>
#include <string.h> 
int main(){
	int a, b;
	while(scanf("%d%d", &a, &b) != EOF){
		char str1[15], str2[15];
		int answer = 0, a1[15], a2[15];
		sprintf(str1, "%d", a);
		sprintf(str2, "%d", b);
		for(int i = 0; i < strlen(str1); i++)
			a1[i] = str1[i] - '0';
		for(int i = 0; i < strlen(str2); i++)
			a2[i] = str2[i] - '0';
		for(int i = 0; i < strlen(str1); i++){
			for(int j = 0; j < strlen(str2); j++){
				answer += a1[i] * a2[j];
			}
		}
		printf("%d\n", answer);
	}
	return 0;
} 

solution4

#include <stdio.h>
#include <string.h> 
int main(){
	char a[20], b[20];
	while(scanf("%s%s", a, b) != EOF){
		int sum = 0;
		for(int i = 0; i < strlen(a); i++)
			for(int j = 0; j < strlen(b); j++)
				sum += (a[i] - '0') * (b[j] - '0');
		printf("%d\n", sum);
		memset(a, '\0', sizeof(a));
		memset(b, '\0', sizeof(b));
	}
	return 0;
} 

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值