Home > Mobile >  How do you check how many times each digit from 0 - 9 appears in an input number
How do you check how many times each digit from 0 - 9 appears in an input number

Time:12-21

I just can't seem to come up with a way to go about this problem. I've been searching online for logic for this but no luck. One way would be to store the number in an array then comparing each value of the array but in this case your only limited to enter a limited amount of digits because of the size of the array and all.

pls help!

EDIT: Thanks for the suggested question but unfortunately I was too dumb to understand how it worked by just looking at the code :( I'm here to learn how to actually do this which is why I need explanations on doing it that way and I couldn't find any explanations there. Not to mention it was C code :p.

EDIT 2: I finally get it. After reading through what @rturrado said several times and wrecking my brain to actually make sense of this. After that I did a couple random numbers with that method. Now that I finally know how to go through each digit in an integer, I can finally go about checking the frequency by using a loop for each digit from 0 - 9. In this loop I'd run through the whole integer number for each iteration and plus one to a variable each time each time any digit in the number is equal to the outer loop variable.

Annnd.....I'm just gonna leave this here incase another poor sod like me comes around trying to make sense of things :)

CodePudding user response:

I understand that you would like to have an explanation and not just a code dump or some comments.

So, let me try to explain you.

As you know: Numbers like 12345 in a base 10 numbering system or decimal system are build of a digit and a power of 10. Mathematically you could write 12345 also a 5*10^0 4*10^1 3*10^2 2*10^3 1*10^4.

Or, we can write:

number = 0;
number = number   1;
number = number * 10;
number = number   2;
number = number * 10;
number = number   3;
number = number * 10;
number = number   4;
number = number * 10;
number = number   5;

That is nothing new. But it is important to understand, how to get back the digits from a number.

Obviously we need to make an integer division by 10 somewhen. But this alone does not give us the digits. If we perform a division o 12345 by 10, then the result is 1234.5. And for the intger devision it os 1234 with a rest of 5. And now, we can see that the rest is the digit that we are looking for.

And in C we have a function that gives us the rest of an integer division. It is the modulo operator %.

Let us look, how this works:

int number = 12345;
int digit = number % 10;     // Result will be 5

// Do something with digit

number = number / 10;   // Now number is 1234 (Integer division will truncate the fraction)
digit = number % 10;        // Result is now 4

// Do something with digit

number = number / 10;   // Now number is 123 (Integer division will truncate the fraction)
digit = number % 10;        // Result is now 3

// Do something with digit

number = number / 10;   // Now number is 12 (Integer division will truncate the fraction)
digit = number % 10;        // Result is now 2

// Do something with digit

number = number / 10;   // Now number is 1 (Integer division will truncate the fraction)
digit = number % 10;        // Result is now 1


number = number / 10;   // Now number is 0, and we can stop the operation.

And later we can do all this in a loop.

Like with

int number = 12345;
while (number > 0) {
    int digit = number % 10;     // Extract next digit from number

    // Do something with digit

    number /= 10;
}

And thats it. Now we extracted all digits.


Next is counting. We have 10 different digits. So, we could now define 10 counter variables like "int counterFor0, counterFor1, counterFor2 ..... , counterFor9" and the compare the digit with "0,1,2,...9" and then increment the related counter. But that is too much typing work.

But, luckily, we have arrays in C . So we can define an array with 10 counters like: int counterForDigit[10]. OK, understood.

You remember that we had in the above code a comment "// Do something with digit ". And this we will do now. If we have a digit, then we use that as an index in our array and increment the related counter.

So, finally. One possible solution would be:

#include <iostream>

int main() {

    // Test number. Can be anything
    int number = 12344555;

    // Counter for our digits
    int counterForDigits[10]{};  // The {} will initialize all values in the array with 0  

    // Extract all digits
    while (number > 0) {

        // Get digit
        int digit = number % 10;

        // Increment related counter
        counterForDigits[digit]  ;

        // Get next number
        number /= 10;
    }
    // Show result
    for (int k = 0; k < 10;   k)
        std::cout << k << " : " << counterForDigits[k] << '\n';
}

If you do not want to show 0 outputs, then please add if (counterForDigits[k] > 0) after the for statement.

If you should have further questions, then please ask

CodePudding user response:

I can offer the solution of your problem:

#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <tuple>
using namespace std;
void showContentVector(vector<int>& input)
{
    for(int i=0; i<input.size();   i)
    {
        cout<<input[i]<<", ";
    }
    return;
}
void showContentMap(map<int, int>& input)
{
    for(auto iterator=input.begin(); iterator!=input.end();   iterator)
    {
        cout<<iterator->first<<" : "<<iterator->second<<endl;
    }
    return;
}
void solve()
{
    int number=1004;
    vector<int> digits;
    map<int, int> repetitions;
    while(number)
    {
        digits.push_back(number);
        number/=10;
    }
    cout<<"digits <- ";
    showContentVector(digits);
    cout<<endl;
    for(int i=0; i<digits.size();   i)
    {
        int count=0;
        for(int j=0; j<digits.size();   j)
        {
            if(digits[i]==digits[j])
            {
                  count;
            }
        }
        repetitions.insert(pair<int, int>(digits[i], count));
    }
    cout<<"repetitions <- "<<endl;
    showContentMap(repetitions);
    cout<<endl;
    return;
}
int main()
{
    solve();
    return 0;
}

Here is the result:

digits <- 4, 0, 0, 1, 
repetitions <- 
0 : 2
1 : 1
4 : 1

CodePudding user response:

A simple approach: Assuming you want to get the number of digits of the decimal equivalent of the number, you can convert the int to a string, then count the digit characters:

#include <string>
[...]
char digit = '3'; // or any digit
int num = 321523; // or any number

// convert to decimal string
std::string str_num = to_string(num);

// count digits
int digit_count = 0;
for(int i=0; i<str_num.length(); i  )
    if(str_num[i] == digit)
        digit_count  ;

// digit_count should now be equal to 2

CodePudding user response:

A possible solution:

  • reading your input as a string,
  • checking if the input is a valid number (contains only digits),
  • then counting the digits using an array of 10 elements (one for each digit from 0 to 9).

A couple of notes on the code below:

  1. Why counts[c - '0']? Subscript operator, [], will use a size_t as a parameter. If you don't want to have an access out of the bounds of the array, you should use an index between size_t 0 and 9. But you are reading characters from a string. If you just use a char from '0' to '9' as an index, the corresponding size_t value will be between 48 and 57 (ASCII codes for '0' and '9' char respectively). By subtracting c - '0' you'll end up with an index between size_t 0 and 9. More difficult to explain than to understand I guess!

  2. Notice also counts[c - '0'] returns a reference to the element in the array. That's why counts[c - '0'] actually modifies the array contents.

[Demo]

#include <algorithm>  // all_of
#include <array>
#include <iostream>  // cout

int main()
{
    auto is_digit = [](char c) { return c >= '0' and c <= '9'; };

    const std::string n{"122333444455555"};

    if (not std::all_of(std::cbegin(n), std::cend(n), is_digit))
    {
        std::cout << "Error: input string is not a valid number.\n";
        return 0;
    }

    std::array<int, 10> counts{};
    for (auto c : n)
    {
        counts[c - '0']  ;
    }
    for (int i{0}; i < counts.size();   i)
    {
        std::cout << "Number of " << i << "s in input number: " << counts[i] << "\n";
    }
}
  •  Tags:  
  • c
  • Related