PTA 1021 B: single-digit Statistics

 

This solution is a solution :( be solved by the processed, when the input number is too large not pass)

#include <iostream>

using namespace std;

int main()
{
	long n; //n为输入的正整数
	cin >> n;
	int end; //end为数的末尾数字

	//数组a用来存储0到9的数量
	int a[10] = {0,0,0,0,0,0,0,0,0,0};

	int j = 0;

	//依此比较该数的末尾数字
	while (n>0)
	{
		end = n % 10;
		n = n / 10;
		for ( j = 0; j < 10; j++)
		{
			if (end==j)
			{
				a[j]++;
			}
		}
	}

	//按升序序列输出每个数的个数
	int i = 0;
	for ( i = 0; i < 10; i++)
	{
		if (a[i]>0)
		{
			cout << i << ":" << a[i] << endl;
		}
	}
	  
	return 0;
}

Solution two :( the process performed by solving a string process, is no longer bound by the size of the figures, by all data)

#include <iostream>
#include <string>

using namespace std;

int main() {

	//将题中所述的整数按字符串形式输入
	string s;
	cin >> s;

	//数组a用于存储0到9的每个数字的个数
	int a[10] = { 0 };

	for (int i = 0; i < s.size(); i++) {
		a[s[i] - '0']++;
	}

	for (int i = 0; i < 10; i++) {
		if (a[i]>0)
		{
			cout << i << ":" << a[i] << endl;
		}
	}

	return 0;
}

 

Published 36 original articles · won praise 47 · views 2150

Guess you like

Origin blog.csdn.net/weixin_43699840/article/details/104685862