一、题目描述
给定一个 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 main()
{
string s;
cin >> s;
int count[10] = {0};
for(char i : s){
count[i - '0']++;
}
for(int j = 0;j < 10;j++){
if(count[j] != 0){
cout << j << ":" << count[j] << endl;
}
}
}
或者用最朴素的方法一个一个输出
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string s;
cin >> s;
vector<int> list0,list1,list2,list3,list4,list5,list6,list7,list8,list9;
for(char i : s){
if((i - '0') == 0){
list0.push_back(s[i]);
}
}
if(!list0.empty()){
cout << "0" << ":" << list0.size();
cout << endl;
}
for(char i : s){
if((i - '0') == 1){
list1.push_back(s[i]);
}
}
if(!list1.empty()){
cout << "1" << ":" << list1.size();
cout << endl;
}
for(char i : s){
if((i - '0') == 2){
list2.push_back(s[i]);
}
}
if(!list2.empty()){
cout << "2" << ":" << list2.size();
cout << endl;
}
for(char i : s){
if((i - '0') == 3){
list3.push_back(s[i]);
}
}
if(!list3.empty()){
cout << "3" << ":" << list3.size();
cout << endl;
}
for(char i : s){
if((i - '0') == 4){
list4.push_back(s[i]);
}
}
if(!list4.empty()){
cout << "4" << ":" << list4.size();
cout << endl;
}
for(char i : s){
if((i - '0') == 5){
list5.push_back(s[i]);
}
}
if(!list5.empty()){
cout << "5" << ":" << list5.size();
cout << endl;
}
for(char i : s){
if((i - '0') == 6){
list6.push_back(s[i]);
}
}
if(!list6.empty()){
cout << "6" << ":" << list6.size();
cout << endl;
}
for(char i : s){
if((i - '0') == 7){
list7.push_back(s[i]);
}
}
if(!list7.empty()){
cout << "7" << ":" << list7.size();
cout << endl;
}
for(char i : s){
if((i - '0') == 8){
list8.push_back(s[i]);
}
}
if(!list8.empty()){
cout << "8" << ":" << list8.size();
cout << endl;
}
for(char i : s){
if((i - '0') == 9){
list9.push_back(s[i]);
}
}
if(!list9.empty()){
cout << "9" << ":" << list9.size();
}
}
一样可以AC;