Search code examples
c#digits

What number is a specified digit and how many of them are there in a number?


Ok, so at first, I'm very beginner in programming. It's my school homework and I cannot use conversion to string. Just if,else,for,while.

On input there is the number and the digit.

I know how to get information what number is a specified digit in a number but I have no idea how to find out how many of these numbers are there.

Let's say I have number 123 467 (it has to be less than 999 999) and I want the third number. I know it's bigger than 100 000, so I do the math - (int) 123 467 / 100 = 123 and then 123%10 = 3. Now I need to know if there are any more 3's in the number - but here is the point - I'm not sure what cycle should I use.

And I also have to create some code which determines how large is the number (bigger than 100/1000/10000/...).

I'm not asking for a full solution but little help would be appreciated. Even in a pseudolanguage.

Current code (almost nothing):

double digit, number;

try
{
    digit = Convert.ToInt32(poledigit.Text);
    number = Convert.ToInt32(polenumber.Text);
}
catch
{
    MessageBox.Show("Zadejte číslo ve správném formátu");
    return;
}

if (digit > 6 & number > 999999)
{
    MessageBox.Show("Číslo musí být menší než 999 999 a digit musí být menší než 6.");
    return;
}

while(number >= 100000)
{
    number /= Math.Pow(10, digit);
    number %= 10;
}

Solution

  • You can iterate through the digits as follows:

    int digitToSearch = 3;
    int count = 0;
    while (number != 0)
    {
        int digit = number % 10;
        if (digit == digitToSearch)
            count++;
        number /= 10;
    }