Monthly Archives: March 2017

Count Digits

You are given a string S. Count the number of occurrences of all the digits in the string S.

 

 

#include <iostream>
using namespace std;

int main()
{ int a = 0, b = 0, c = 0, d = 0, e = 0,f=0,g=0,h=0,i=0,j=0;
    string s;
    // Read given string from STDIN
    cin >> s;

    int s_len = s.length();
    // Iterate over each character in the string
    for(int k=0; k<s_len; k++) {

        // This can be done in a better way using hashing, which simplifies the implementation,
        // however for the purpose of this article we'll restrict the implementation to naive way

        // Check for each character in if else
        if(s[k] == '0') {
            a++;
        } else if(s[k] == '1') {
            b++;
        } else if(s[k] == '2') {
            c++;
        } else if(s[k] == '3') {
            d++;
        } else if(s[k] == '4') {
            e++;
        }
        else if(s[k] == '5') {
            f++;
        }
        else if(s[k] == '6') {
            g++;
        }
        else if(s[k] == '7') {
            h++;
        }
        else if(s[k] == '8') {
            i++;
        }
        else if(s[k] == '9') {
            j++;
        }
    }
    // Print out the result to STDOUT
    cout << "0 " << a << endl;
    cout << "1 " << b << endl;
    cout << "2 " << c << endl;
    cout << "3 " << d << endl;
    cout << "4 " << e << endl;
    cout << "5 " << f << endl;
    cout << "6 " << g << endl;
    cout << "7 " << h << endl;
    cout << "8 " << i << endl;
    cout << "9 " << j << endl;
    
    return 0;
}