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;
}
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值