給定一個 k 位整數
請撰寫程式統計每種不同的個位數字出現的次數,例如:給定 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
AC代碼(C++):
方法一(列舉了所有的情況,看起來有點兒傻…哈哈哈)
#include <iostream>
#include <string.h>
char str[1005];
using namespace std;
int main()
{
while( cin>>str )
{
int k0=0,k1=0,k2=0,k3=0,k4=0,k5=0,k6=0,k7=0,k8=0,k9=0;
for( int i=0;str[i]!='\0';i++)
{
if( str[i]=='0' )
{
k0++;
}
else if( str[i]=='1' )
{
k1++;
}
else if( str[i]=='2' )
{
k2++;
}
else if( str[i]=='3' )
{
k3++;
}
else if( str[i]=='4' )
{
k4++;
}
else if( str[i]=='5' )
{
k5++;
}
else if( str[i]=='6' )
{
k6++;
}
else if( str[i]=='7' )
{
k7++;
}
else if( str[i]=='8' )
{
k8++;
}
else if( str[i]=='9' )
{
k9++;
}
}
if( k0!=0 )
{
cout<<"0:"<<k0<<endl;
}
if( k1!=0 )
{
cout<<"1:"<<k1<<endl;
}
if( k2!=0 )
{
cout<<"2:"<<k2<<endl;
}
if( k3!=0 )
{
cout<<"3:"<<k3<<endl;
}
if( k4!=0 )
{
cout<<"4:"<<k4<<endl;
}
if( k5!=0 )
{
cout<<"5:"<<k5<<endl;
}
if( k6!=0 )
{
cout<<"6:"<<k6<<endl;
}
if( k7!=0 )
{
cout<<"7:"<<k7<<endl;
}
if( k8!=0 )
{
cout<<"8:"<<k8<<endl;
}
if( k9!=0 )
{
cout<<"9:"<<k9<<endl;
}
}
return 0;
}
方法二
#include<iostream>
#include<string>
using namespace std;
int main(){
int a[10]={0};
string s;
cin>>s;
for(int i=0;i<s.size();i++){
switch(s[i]){
case '0':a[0]++;break;
case '1':a[1]++;break;
case '2':a[2]++;break;
case '3':a[3]++;break;
case '4':a[4]++;break;
case '5':a[5]++;break;
case '6':a[6]++;break;
case '7':a[7]++;break;
case '8':a[8]++;break;
case '9':a[9]++;break;
}
}
for(int i=0;i<=9;i++){
if(a[i])cout<<i<<":"<<a[i]<<endl;
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/208778.html
標籤:其他
上一篇:關于機械鍵盤的一些基礎知識
