[pat乙]1021. 个位数统计 原创

1021. 个位数统计 (15)

给定一个k位整数N = dk-110k-1 + … + d1101 + d0 (0<=di<=9, i=0,…,k-1, dk-1>0),请编写程序统计每种不同的个位数字出现的次数。例如:给定N = 100311,则有2个0,3个1,和1个3。

输入格式:

每个输入包含1个测试用例,即一个不超过1000位的正整数N。

输出格式:

对N中每一种不同的个位数字,以D:M的格式在一行中输出该位数字D及其在N中出现的次数M。要求按D的升序输出。

输入样例:

100311

输出样例:

0:2
1:3
3:1

#include <iostream>
#include <string>
using namespace std;


int C0 = 0, C1 = 0, C2 = 0, C3 = 0, C4 = 0, C5 = 0, C6 = 0, C7 = 0, C8 = 0, C9 = 0;
void countN(string N)
{
	for (int i = 0; i < N.size(); i++)
	{
		if (N[i] - '0' == 0)
			C0++;
		else if (N[i] - '0' == 1)
			C1++;
		else if (N[i] - '0' == 2)
			C2++;
		else if (N[i] - '0' == 3)
			C3++;
		else if (N[i] - '0' == 4)
			C4++;
		else if (N[i] - '0' == 5)
			C5++;
		else if (N[i] - '0' == 6)
			C6++;
		else if (N[i] - '0' == 7)
			C7++;
		else if (N[i] - '0' == 8)
			C8++;
		else if (N[i] - '0' == 9)
			C9++;
	}

}

void printN()
{
	if (C0)
		cout << "0:" << C0 << endl;
	if (C1)
		cout << "1:" << C1 << endl;
	if (C2)
		cout << "2:" << C2 << endl;
	if (C3)
		cout << "3:" << C3 << endl;
	if (C4)
		cout << "4:" << C4 << endl;
	if (C5)
		cout << "5:" << C5 << endl;
	if (C6)
		cout << "6:" << C6 << endl;
	if (C7)
		cout << "7:" << C7 << endl;
	if (C8)
		cout << "8:" << C8 << endl;
	if (C9)
		cout << "9:" << C9 << endl;
}

int main()
{
	string N;
	cin >> N;

	countN(N);
	printN();
	return 0;
}
2 桶计数
#include <iostream>
#include <string>
using namespace std;

int Cnt[10] = {0};
void countN(string N)
{
	for (int i = 0; i < N.size(); i++)
		for (int j = 0; j < 10; j++)
			if (N[i] - '0' == j)
				Cnt[j]++;

}

void printN()
{
	for (int i = 0; i < 10; i++)
		if (Cnt[i])
			cout << i << ':' << Cnt[i] << endl;
}

int main()
{
	string N;
	cin >> N;
	
	countN(N);
	printN();

	return 0;
}
posted @ 2023-07-05 16:10  俺叫西西弗斯  阅读(0)  评论(0)    收藏  举报  来源