nkash
nkash

Reputation: 3

How to find occurences of a digit with 4 in it within 50?

I want to know how to find the number of times that 4 occurs within a certain range; lets say 50 for example. Therefore if the input is the range 50, then output should look like 4,14,24,34,40,41,...,49.

Now its pretty easy to find the first half of the output that is 4,14,..so on,i.e digits ending with 4,

     for(i=0;i<=50;i++)
        if(i%10==4)
        {
          printf("%d",i);
        }

but what about starting with 4? Can the problem be solved using regular expressions?

Upvotes: 0

Views: 40

Answers (3)

Adrian Shum
Adrian Shum

Reputation: 40056

The idea is simple: check the ending digit to see if it is 4, if not, keep dividing the number by 10 until the last digit is 4, or the number is 0.

It is equally easy to do in iterative or recursive approach:

Pseudo code (Iterative):

boolean contains4(int input) {
    while (input > 0) {
        if (i % 10 == 4) {
            return true;
        }
        input /= 10;
    }
    return false;
}

Pseudo-code (Recursive):

boolean contains4(int input) {
    if (input == 0) {
        return false;
    } else if (input % 10 == 4) {
        return true;
    } else {
        return contains4(input / 10);
    }
}

Upvotes: 0

shree.pat18
shree.pat18

Reputation: 21757

You could try to use a function that repeatedly tests each digit in the number to see if it is equal to 4, like so:

int check4(int x)
{
  //Units place
    if (x==0)
    {
      return 0;
    }
    else if (x%10 == 4)
    {
      return 1;
     }
 //Divide by 10 so that tens place is now unit place; repeat till no more tens place
    else
    {
     return check4(x/10);
    }
 }

This solution completely eschews the need for string processing.

Demo

Upvotes: 2

hjpotter92
hjpotter92

Reputation: 80647

No need for regex at all. Store the integer as a string in temporary variable, and then use strstr.

for( i = 0; i <= input; i++ ) {
    char str[20];
    sprintf( str, "%d", i );
    if( strstr(str, "4") )
        printf( "%d ", i );
}

Here's a demo on codepad.

Upvotes: 1

Related Questions