Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a number has repeated digits

Tags:

javascript

How to check if a digit appears more than once in a number (anywhere within it)?


Example input numbers:

1, 10, 11, 1010, 1981

Output should tell which of them has any repeated digits:

false, false, true, true, true

Publihsed all the good answers given in a jsperf page

like image 627
vsync Avatar asked Sep 19 '25 16:09

vsync


2 Answers

I think the fastest way would be a RegExp test. You can use it to get a quick true or false on whether there is a repeat, and it's compact enough to use in conditional operators. Here's an example that'd work with numbers and strings of numbers.

function hasRepeatingdigits(N) {
  return (/([0-9]).*?\1/).test(N)
}  

console.log(
[1, 10, 11, 1010, 1981, 12345678901, 123456789].map(hasRepeatingdigits)
)

(Edit -Isaac B)

Here's a breakdown of how the RegExp works:

  • The [0-9] creates a list of single characters between 0 and 9 to be matched.
  • Adding the parentheses ([0-9]) defines this list as the first capture group. These parens would not be needed if you were only searching for a char and didn't need the RegExp to perform a subsequent action. (i.e. /[0-9]/ is all you need to find the first index of a char 0 through 9 in a string, or true in a RegExp test)
  • The . matches any single char - except for line terminators. Adding the lazy quantifier *? matches between 0 and infinity times, as few time as possible.
  • The \1 matches the same text as most recently matched by the first capture group

In summary: /([0-9]).*?\1/ is a regular expression that iterates through a string looking for each char 0 through 9 and returning a match the first time a match is found to the char currently in the first capture group.

In the string '123432', this RexExp would return a full match: '2343' on capture group 1: '2'.

RegExp.prototype.test() searches a string using the provided RegExp and returns true if the RegExp return a match, else it returns false. This could easily be modified to find a duplicate letter char as well using /([A-Za-z]).*?\1/).test(N).

Beyond the very useful MDN section on RegExp, I highly recommend people working to get more comfortable with them to check out this RegularExpressions101 tool.

like image 155
Isaac B Avatar answered Sep 22 '25 04:09

Isaac B


function checkForRepeatingDigits(N){
 var arr = (''+N).split(''),
     result = arr.filter((elem, i) => arr.indexOf(elem) == i);

 return result.length != (''+N).length;
}

// Or
function checkForRepeatingDigits(N){
    return [...new Set((''+N).split(''))].length != (''+N).length;
}

console.log([1, 10, 11, 1010, 1981].map(checkForRepeatingDigits))
like image 39
vsync Avatar answered Sep 22 '25 04:09

vsync