What is the fastest way to check for repeated digits of a number?

Let's say I want to check if the number n = 123 has duplicate digits. I tried:

#include <iostream>

using namespace std;

int main() {
    int n = 123;
    int d1 = n % 10;
    int d2 = ( n / 10 ) % 10;
    int d3 = ( n / 100 ) % 10;
    if( d1 != d2 && d1 != d3 && d2 != d3 ) {
        cout << n << " does not have duplicate digits.\n";
    }
}

Is there a faster solution to this problem?

Update
Sorry for the ambiguity. The code above was written in C ++ just to describe the purpose. I have to solve this problem in TI-89 with 9 digits. And since the limitation of memory and speed, I am looking for a quick way.

TI-89 has only a few keywords:

  • If
  • If ... Then
  • when (
  • For ... EndFor
  • Bye ... EndWhile
  • Loop ... EndLoop
  • Custom ... EndCustom

Thanks
Chan

+5
source share
3 answers

, ( , - "measure, don't guess"). , , , .

int hasDupes (unsigned int n) {
    // Flag to indicate digit has been used.

    int i, used[10];

    // Must have dupes if more than ten digits.

    if (n > 9999999999)
        return 1;

    // Initialise dupe flags to false.

    for (i = 0; i < 10; i++)
        used[i] = 0;

    // Process all digits in number.

    while (n != 0) {
        // Already used? Return true.

        if (used[n%10])  // you can cache n%10 if compiler not too smart.
            return 1;

        // Otherwise, mark used, go to next digit.

        used[n%10] = 1;  // and you would use cached value here.
        n /= 10;
    }

    // No dupes, return false.

    return 0;
}

, .

, 0 999:

const int *hasDupes = {
//  0  1  2  3  4  5  6  7  8  9
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  //   x
    0, 1, 0, 0, 0, 0, 0, 0, 0, 0,  //  1x
    0, 0, 1, 0, 0, 0, 0, 0, 0, 0,  //  2x
    :
    0, 0, 0, 0, 0, 0, 0, 1, 0, 1,  // 97x
    0, 0, 0, 0, 0, 0, 0, 0, 1, 1,  // 98x
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  // 99x
};

hasDupes[n].


, , ( ), , : -)

.

+10
template<class T, int radix = 10>
bool has_duplicate_digits(T n) {
    int digits_mask = 0;
    while (digits_mask |= (1 << (n % radix)), n /= radix)
        if (digits_mask & (1 << (n % radix)))
            return true;
    return false;
}

- , n , int radix .


digits_mask - - ( 0 0, 1 1 ..).

n, . , , true, .

, false.

1 << x 1, 2, 4, 8 ..: , / .

a |= z a = a | z, a z.

a & z - a z (false), (true), .

+2

I did a crash course in the base TI-89 to answer :)

Let's see if this works (I don’t have an emulator, so I can’t check).

Test()
Prgm
{0,0,0,0,0,0,0,0,0,0}->A
Title "Request"
Request "Enter a number",B
EndDlog
Expr(B)->B
While  B > 1
 MOD(10,B)->C
 if A[C+1] = 1 goto K 
 1->A[C+1]
 B-C->B 
EndWhile
Title "Done"
Text "Numbers non repeating"
Enddlog
goto J

Lbl K
Title "Done"
Text "Numbers repeating"
Enddlog

Lbl J
EndPrgm
+1
source

All Articles