部分A+B(B1016)

题目:https://www.patest.cn/contests/pat-b-practise/1016

正整数A的“DA(为1位整数)部分”定义为由A中所有DA组成的新整数PA。例如:给定A = 3862767,DA = 6,则A的“6部分”PA是66,因为A中有2个6。

现给定A、DA、B、DB,请编写程序计算PA + PB

输入格式:

输入在一行中依次给出A、DA、B、DB,中间以空格分隔,其中0 < A, B < 1010

输出格式:

在一行中输出PA + PB的值。

输入样例1:
3862767 6 13530293 3
输出样例1:
399
输入样例2:
3862767 1 13530293 8
输出样例2:
0

我的思路是以“字符串”来考虑的,代码实现如下,较为复杂:

 
 
#include <stdio.h>
#include <string.h>

int main(){
	char str1[20], str2[20];
	char c1, c2;
	int n1, l1 = 0, n2, l2 = 0;
	long long pa, pb;
	scanf("%s %c %s %c", str1, &c1, str2, &c2);
	n1 = strlen(str1);
	n2 = strlen(str2);
	while (n1--){
		if (str1[n1] == c1){
			l1++;
		}
	}
	while (n2--){
		if (str2[n2] == c2){
			l2++;
		}
	}
	if (!l1){
		pa = 0;
	}
	else{
		str1[l1] = '\0';
		while (l1--){
			str1[l1] = c1;
		}
		sscanf(str1, "%lld", &pa);
	}
	if (!l2){
		pb = 0;
	}
	else{
		str2[l2] = '\0';
		while (l2--){
			str2[l2] = c2;
		}
		sscanf(str2, "%lld", &pb);
	}

	printf("%lld", pa + pb);
	return 0;
}

 
 

1、字符数组“%s”,字符“%c”。

2、int类型的大致范围是-2*10^9-2*10^9,long long的大致范围是-9*10^18-9*10^18。


另一种思路是直接将数据作为long long类型来处理,代码为:

 
 
#include <stdio.h>

int main(){
	long long a, b, pa=0, pb=0;
	int da, db;
	scanf("%lld %d %lld %d", &a, &da, &b, &db);
	while(a){
		if (a % 10 == da){
			pa = pa * 10 + da;
		}
		a /= 10;
	}
	while (b){
		if (b % 10 == db){
			pb = pb * 10 + db;
		}
		b /= 10;
	}
	printf("%lld", pa + pb);
	return 0;
}

 
 
1、while(b)等价于while(b != 0)


猜你喜欢

转载自blog.csdn.net/chenxjhit/article/details/74479821