Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to check if a number contains another number

Tags:

javascript

For example if the number 752 contains the number 5? Whats the best way to check? Convert to string or divide into individual digits?

like image 873
user3312156 Avatar asked Jul 29 '15 14:07

user3312156


People also ask

How do you check if a number has a digit?

bool containsDigit(int number, int digit); If number contains digit, then the function should return true . Otherwise, the function should return false .

What is a Duodigit?

We call a natural number a duodigit if its decimal representation uses no more than two different digits. For example, , and are duodigits, while is not. It can be shown that every natural number has duodigit multiples. Let be the smallest (positive) multiple of the number that happens to be a duodigit.


2 Answers

Convert to string and use indexOf

(752+'').indexOf('5') > -1

console.log((752+'').indexOf('5') > -1);
console.log((752+'').indexOf('9') > -1);
like image 175
AmmarCSE Avatar answered Sep 19 '22 18:09

AmmarCSE


Convert to string and use one of these options:

indexOf():

(number + '').indexOf(needle) > -1;

includes():

(number + '').includes(needle);
like image 29
Halfacht Avatar answered Sep 20 '22 18:09

Halfacht