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

L1-003 个位数统计 (15分)
给定一个 k 位整数 N=dk−110k−1+⋯+d1101+d0(0⩽d1⩽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
#include
#include
#include
using namespace std;

int main(){
// int n;
// cin>>n;
// string s = to_string(n);
  string s;
  cin>>s;
  vector<int> v;

  
// to_string()将 int、double、long等转化为string
//int a = 4;
//double b = 3.14;
//string str1, str2;
//str1 = to_string(a);
//str2 = to_string(b);
//cout << str1 << endl;
//cout << str2 << endl;

//string转int 
//string s1("1234567");
//char* s2 = "1234567";
//int a = stoi(s1);
//int b = atoi(s2);
//int c = atoi(s1.c_str());
//cout << a << endl;
//cout << b << endl;
//cout << c << endl;
//
//char与int 1-9互换 
//int i=9;
//char i_ch=i+'0';//此时i_ch='9'
//
//char ch='9';
//int ch_int=ch-'0';//此时ch_int=9

 for(int i = 0;i<s.length();i++){
 	char temp = s[i] ;
    int num  = temp - '0';
   v.push_back(num);
 }
    int cnt[10];
     cnt[0] = count(v.begin(), v.end(), 0);
     cnt[1] = count(v.begin(), v.end(), 1);
     cnt[2] = count(v.begin(), v.end(), 2);
     cnt[3]= count(v.begin(), v.end(), 3);
	 cnt[4]= count(v.begin(), v.end(), 4);
	 cnt[5]= count(v.begin(), v.end(), 5);
     cnt[6]= count(v.begin(), v.end(), 6);
     cnt[7]= count(v.begin(), v.end(), 7);
     cnt[8]= count(v.begin(), v.end(), 8);
     cnt[9]= count(v.begin(), v.end(), 9);
 
 for(int i = 0;i<10;i++){
 	if(cnt[i]!=0){
 		cout<<i<<":"<<cnt[i]<<endl; 
	 }
 }

return 0;
}

还想着用to_string()把读入的int转为string,然而int表示的范围是2的32次方,int的范围是-2147483648~2147483647,题目可是1000位,导致测试点2没过。。。
直接以string类型输入数字就行了

你可能感兴趣的:(C++,PTA)