Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a int var contains a specific number

Tags:

c

char

int

numbers

How to check if a int var contains a specific number

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

Thanks for your help ;)

like image 712
c5754272 Avatar asked Feb 12 '11 10:02

c5754272


People also ask

How check if an integer contains an number in C++?

Using built-in method isdigit(), each character of string is checked. If the string character is a number, it will print that string contains int. If string contains character or alphabet, it will print that string does not contain int.

How do you check if a variable contains an integer?

isInteger() Method. The Number isInteger() method takes the variable as a parameter and returns the true if the variable is an integer. Otherwise, it returns false.

Can I use Isdigit for int?

Function isdigit() takes a single argument in the form of an integer and returns the value of type int .

How do you check if a number contains a certain number in Java?

To find whether a given string contains a number, convert it to a character array and find whether each character in the array is a digit using the isDigit() method of the Character class.


1 Answers

457 % 10 = 7    *

457 / 10 = 45

 45 % 10 = 5    *

 45 / 10 = 4

  4 % 10 = 4    *

  4 / 10 = 0    done

Get it?

Here's a C implementation of the algorithm that my answer implies. It will find any digit in any integer. It is essentially the exact same as Shakti Singh's answer except that it works for negative integers and stops as soon as the digit is 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;
    }
}
like image 188
matt.dolfin Avatar answered Oct 13 '22 20:10

matt.dolfin