Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

c++ - How to find the frequency of digits in a number using a switch statement?

For my college intro to computer science class we must write a program which outputs frequency of digits in a given integer. For example, if the number is 124243294 the output is:

Number Frequency
1      1
2      3
3      1
4      2
9      1

You must use the switch statement to obtain the frequency of the digits.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could do something like this:

int number;
std::cin >> number;

std::string s = std::to_string(number);
int freq[10] = {};

for(char ch : s)
{
    switch (ch)
    {
        case '0':
        case '1':
        case '2':
        case '3':
        case '4':
        case '5':
        case '6':
        case '7':
        case '8':
        case '9':
            freq[ch - '0']++;
            break;
    }
}

std::cout << "Number Frequency
";
for(int i = 0; i < 10; ++i)
{
    if (freq[i] != 0)
        std::cout << std::setw(7) << std::left << i << freq[i] << "
";
}

Demo

But, why must a switch be used? I would use a std::(unordered_)map instead, eg:

int number;
std::cin >> number;

std::string s = std::to_string(number);
std::map<char, int> freq;

for(char ch : s) {
    freq[ch]++;
}

std::cout << "Number Frequency
";
for(auto &elem : freq) {
    std::cout << std::setw(7) << std::left << elem.first << elem.second << "
";
}

Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...