L1-003 个位数统计
问题描述
错误代码
#include<iostream>
using namespace std;
int main()
{
long long int n,m = 10,num;
cin >> n;
int a[10];
for(int i = 0; i < 10; i++) {
a[i] = 0;
}
while((m/10) <= n) {
num = n % m;
num = num / (m / 10);
a[num]++;
m *= 10;
}
for(int i = 0; i < 10; i++) {
if(a[i] != 0)
cout << i << ":" << a[i] << endl;
}
return 0;
}
没仔细看题目,导致部分结果通过,题目要求不超过1000位的,肯定不能用算数了,要用到字符串。
代码
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s;
cin >> s;
int a[10];
for (int i = 0; i <= 9; i++)
a[i] = 0;
int len = s.length();
for (int i = 0; i < len; i++)
{
a[s[i]-'0']++;
}
for (int i = 0;i <= 9; i++)
{
if (a[i])
cout << i << ":" << a[i] << endl;
}
return 0;
}