L1-003 个位数统计 (15分)三种方法解析

题目链接:https://pintia.cn/problem-sets/994805046380707840/problems/994805143738892288
在这里插入图片描述
第一种方法:
调用getchar()时,用户输入的字符被存放在键盘缓冲区中,直到用户输入回车(\n),getchar才开始从stdin流中每次读入一个字符

#include<iostream>
using namespace std;
int main()
{
	char c;
	int a[15]={0};
	while((c = getchar() )!= '\n')//一直循环,直到用户输入回车 
	{
		a[c-'0']++;
	}
	for(int i=0;i<10;i++)
	if(a[i]!=0) cout<<i<<":"<<a[i]<<endl;
	return 0;
}

第二种方法:
因为map的关键字是自动排序的,利用这个特点,也可以做此题

#include <iostream>
#include <map>
#include<string.h>
using namespace std;
map<int, int> mp;

int main() 
{
	char c[1005];
	scanf("%s", c);
	for (int i = 0;i<strlen(c); i++) 
	{
		mp[c[i] - '0']++;
	}
	map<int, int>::iterator it = mp.begin();
	while (it != mp.end()) {
		cout << it->first << ":" << it->second << endl;
		it++;
	}
	return 0;
}

第三种方法:
麻烦…但容易理解吧

#include<iostream>
#include<string.h>
using namespace std;
int main()
{
	char N[1005];
	char x;
    int b,c=0,d=0,e=0,f=0,g=0,h=0,j=0,o=0,p=0,q=0;
	cin>>N;
	for(int i=0;i<strlen(N);i++)
	{
	    x=N[i];
		if(x=='0')
		c++;
		if(x=='1')
		d++;	
		if(x=='2')
		e++;
		if(x=='3')
		f++;
		if(x=='4')
		g++;
		if(x=='5')
		h++;
		if(x=='6')
		j++;
		if(x=='7')
		o++;
		if(x=='8')
		p++;
		if(x=='9')
		q++;		
	}
	if(c>0)
	cout<<"0:"<<c<<endl;
	if(d>0)
	cout<<"1:"<<d<<endl;
	if(e>0)
	cout<<"2:"<<e<<endl;
	if(f>0)
	cout<<"3:"<<f<<endl;
	if(g>0)
	cout<<"4:"<<g<<endl;
	if(h>0)
	cout<<"5:"<<h<<endl;
	if(j>0)
	cout<<"6:"<<j<<endl;
	if(o>0)
	cout<<"7:"<<o<<endl;
	if(p>0)
	cout<<"8:"<<p<<endl;
	if(q>0)
	cout<<"9:"<<q<<endl;
	return 0;
}
发布了68 篇原创文章 · 获赞 142 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/wmy0217_/article/details/104246754