題目:

思路:
定義一個整型數組進行計數,其下標對應的數組值就是數字0~9相應出現的次數。
代碼(C++版):
1 #include <iostream> 2 #include <string> 3 using namespace std; 4 5 int main() 6 { 7 string n; 8 cin >> n; 9 int cnt[10] = {0}; 10 for(int i = 0; i < n.length(); i++) 11 { 12 cnt[n.at(i) - '0']++; 13 } 14 for(int i = 0; i <= 9; i++) 15 { 16 if(cnt[i]) 17 cout << i << ":" << cnt[i] << endl; 18 } 19 return 0; 20 }
代碼(C語言版):
1 #include <stdio.h> 2 #include <string.h> 3 4 int main() 5 { 6 char n[1005]; 7 scanf("%s",n); 8 int len = strlen(n); 9 int cnt[10] = {0}; 10 for(int i = 0; i < len; i++) 11 { 12 cnt[n[i] - '0']++; 13 } 14 for(int i = 0; i <= 9; i++) 15 { 16 if(cnt[i]) 17 printf("%d:%d\n", i, cnt[i]); 18 } 19 return 0; 20 }
總結:
靈活運用數組下標與其值的對應關系。
