How to check if int var contains a specific number

How to check if int var contains a specific number

I can not find a solution for this. For example: I need to check if int 457 contains number 5 somewhere.

Thank you for your help;)

+5
source share
3 answers
457 % 10 = 7    *

457 / 10 = 45

 45 % 10 = 5    *

 45 / 10 = 4

  4 % 10 = 4    *

  4 / 10 = 0    done

Get it

Here's the C implementation of the algorithm, which implies my answer. He will find any number in any whole. This is essentially the same as Shakti Singh's answer, except that it works for negative integers and stops as soon as the digit found ...

const int NUMBER = 457;         // This can be any integer
const int DIGIT_TO_FIND = 5;    // This can be any digit

int thisNumber = NUMBER >= 0 ? NUMBER : -NUMBER;    // ?: => Conditional Operator
int thisDigit;

while (thisNumber != 0)
{
    thisDigit = thisNumber % 10;    // Always equal to the last digit of thisNumber
    thisNumber = thisNumber / 10;   // Always equal to thisNumber with the last digit
                                    // chopped off, or 0 if thisNumber is less than 10
    if (thisDigit == DIGIT_TO_FIND)
    {
        printf("%d contains digit %d", NUMBER, DIGIT_TO_FIND);
        break;
    }
}
+13
source

Convert it to a string and check if the string contains the character "5".

+4
int i=457, n=0;

while (i>0)
{
 n=i%10;
 i=i/10;
 if (n == 5)
 {
   printf("5 is there in the number %d",i);
 }
}
+3

All Articles