Check if a number has repeated digits
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))
Checking if a number has any repeated elements
When you call the function repeatCheck()
you don't pass a reference to the variable repeatedNumber
, so any changes to the variable do not affect the original definition of repeatedNumber
. Therefore, the repeatedNumber
defined in numberWorks()
is never updated.
what you could do instead is assign the return
value of repeatCheck
to repeatedNumber
.
repeatedNumber = False
repeatedNumber = repeatCheck(digits)
and rewrite repeatCheck
to return True
or False
upon seeing a repeat:
def repeatCheck(myList):
seen = set()
for number in myList:
if number in seen:
return True
seen.add(number)
return False
This way you circumvent the ambiguity of reusing the variable name repeatedNumber
Check if number has a digit multiple times
If your ultimate goal is simply detecting if there's a double, this function may help:
def has_doubles(n):
return len(set(str(n))) < len(str(n))
How to check if number has a repeating digit using recursion?
#include <iostream>
using namespace std;
bool hasRepeatingDigit(int n, int mask)
{
// base case: if we have checked all the digits and didn't find any duplicates, return false
if (n == 0)
return false;
/*
p is the place of the last digit in n (n%10).
A digit can range from 0 to 9.
The place of 0 will be 1 << 0 which is 1.
The place of 1 will be 1 << 1 which is 2.
The place of 2 will be 1 << 2 which is 4.
...
...
The place of 9 will be 1 << 9 which is 512.
*/
int p = 1 << (n % 10);
// if place of p has already been marked then it's a duplicate
if (mask&p)
return true;
// otherwise scrap the last digit (n/10), mark place p and recurse on the remaining digits
return hasRepeatingDigit(n / 10, mask|p);
}
int main()
{
int n;
cin >> n;
cout << hasRepeatingDigit(n, 0) << endl;
}
Check if integer has repeating digits. No string methods or arrays
Here is a short and sweet version :)
private static boolean hasDistinctDigits(int number) {
int numMask = 0;
int numDigits = (int) Math.ceil(Math.log10(number+1));
for (int digitIdx = 0; digitIdx < numDigits; digitIdx++) {
int curDigit = (int)(number / Math.pow(10,digitIdx)) % 10;
int digitMask = (int)Math.pow(2, curDigit);
if ((numMask & digitMask) > 0) return false;
numMask = numMask | digitMask;
}
return true;
}
It works in a pretty simply way. numMask
is an integer used to store what digits have already been encountered (since a decimal system number has only 10 digits and an integer gives use 16-bits, we have enough bits to store each decimal digit as it occurs).
We loop over all digits in the number. For each digit index, we get the actual digit in curDigit
. Let's say the current digit is 5
. We then check it the 5th bit is raised in out numMask: if it is, then we have already encounter a 5
in the past, so we can immediately tell that the number does not have all distinct digits and return false; otherwise, we modify numMask
and raise the 5th bit.
If we make it to the end, then no dupicate digits were encountered.
What is the fastest way to check for duplicate digits of a number?
Not necessarily faster but you should measure anyway, just in case - my optimisation mantra is "measure, don't guess"
.
But I believe it's clearer in intent (and simple enough to be translated to a simpler calculator language. It's also able to handle arbitrarily sized integers.
int hasDupes (unsigned int n) {
// Flag to indicate digit has been used, all zero to start.
int used[10] = {0};
// More than 10 digits must have duplicates, return true quickly.
if (n > 9999999999) return 1;
// Process each digit in number.
while (n != 0) {
// If duplicate, return true as soon as found.
if (used[n%10]) return 1;
// Otherwise, mark used, go to next digit.
used[n%10] = 1;
n /= 10;
}
// No duplicates after checking all digits, return false.
return 0;
}
If you have a limited range of possibilities, you can use the time-honoured approach of sacrificing space for time. For example, let's say you're talking about numbers between 0 and 999 inclusive (the : :
markers simply indicate data I've removed to keep the size of the answer manageable):
const int *hasDupes = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 9
0, 1, 0, 0, 0, 0, 0, 0, 0, 0, // 10 - 19
0, 0, 1, 0, 0, 0, 0, 0, 0, 0, // 20 - 29
: :
0, 0, 1, 0, 0, 1, 0, 0, 0, 0, // 520 - 529
: :
0, 1, 0, 0, 0, 0, 0, 0, 1, 0, // 810 - 819
: :
0, 0, 0, 0, 0, 0, 0, 1, 0, 1, // 970 - 979
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, // 980 - 989
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 990 - 999
};
and just do a table lookup of hasDupes[n]
. The table itself could be generated (once) programmatically and then just inserted into your code for usage.
However, based on your edit where you state you need to handle nine-digit numbers, a billion-element array is probably not going to be possible on your calculator. I would therefore opt for the first solution.
REGEX to check if a number is repeated in a string
You can use
^(?=.{9}$)(?=.*(\d).*\1)(?:\.*\d){1,9}\.*$
Or, if you need to only allow digits from 1
to 9
:
^(?=.{9}$)(?=.*([1-9]).*\1)(?:\.*[1-9]){1,9}\.*$
See this regex demo.
Details:
^
- start of string(?=.{9}$)
- the string should contain 9 chars(?=.*(\d).*\1)
- there must be a repeating digit(?:\.*\d){1,9}\.*
- 1 to 9 occurrences of any zero or more dots followed with a digit and then any zero or more dots$
- end of string.
Check if any number is repeated, individually, more than N times
Your pattern ([0-9]{5}\1)
uses a backreference to a group that does not exist yet.
In Javascript you will match 5 consecutive digits as according to the documentation stated at the link to the backreference
According to the official ECMA standard, a backreference to a
non-participating capturing group must successfully match nothing..
You could update your pattern to put the capturing group around matching a single digit and then repeat that 4 times to match 5 repeated digits.
([0-9])\1{4}
Regex demo
Related Topics
Validation Using Yup to Check String or Number Length
How to Redirect to Another Page Using Angularjs
Calculate Percentage JavaScript
React Native: Image Not Displaying With Dynamic/Local Uri
Size of Json Object (In Kbs/Mbs)
Jquery - Ajax Returning Error 500 on Some Posts
Typescript Module Has No Exported Members - React
How to Simulate Mouse Click Along With Mouse Move Using JavaScript
How to Replace All Words of Length Less Than 3 in a String With " " (Space) in JavaScript
Displaying Navbar on Multiple HTML Pages Using Bootstrap
Typescript - Possible to Disable Type Checking
How to Make a Auto-Increment Id in My Table Td Using Jquery
React Component Not Re-Rendering When State Changes
Reactjs: Expected Onclick Listener to Be a Function, Instead Got Type String
How to Combine First Name and Last Name in JavaScript
Chat Box, Auto Scroll to Bottom
Javascript Regex Splitting Words in a Comma Separated String