团体程序设计天梯赛-练习集 L1-003 个位数统计 (15分)

    科技2022-07-13  112

    L1-003 个位数统计 (15分)

    请编写程序统计每种不同的个位数字出现的次数。例如:给定 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<cstring> #include<algorithm> using namespace std; string str; int ans[15]; int main(){ char ch; while((ch = getchar())!='\n') ans[ch-'0']++; for(int i = 0; i < 10; i ++) if(ans[i] != 0) cout << i << ":" <<ans[i] << endl; return 0; } #include<iostream> #include<cstring> #include<algorithm> using namespace std; string str; int ans[15]; int main(){ getline(cin, str); for(int i = 0; i < str.length(); i ++) ans[str[i]-'0']++; for(int i = 0; i < 10; i ++) if(ans[i] != 0) cout << i << ":" <<ans[i] << endl; return 0; }
    Processed: 0.016, SQL: 8