algorithm - What is the fastest way to check for duplicate digits of a number? -


let's want check if number n = 123 has duplicate digits. 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 << " not have duplicate digits.\n";     } } 

is there faster solution problem?

update
sorry being unclear. code above written in c++ description purpose. have solve problem in ti-89, number of 9 digits. , since limitation of memory , speed, i'm looking fastest way possible.

ti-89 has several condition keyword:

  • if
  • if ... then
  • when(
  • for ... endfor
  • while ... endwhile
  • loop ... endloop
  • custom ... endcustom

thanks,
chan

faster, possibly not (but should measure anyway, in case - optimisation mantra "measure, don't guess"). clearer in intent, think, yes, , able handle arbitrary sized integers.

int hasdupes (unsigned int n) {     // flag indicate digit has been used.      int i, used[10];      // must have dupes if more ten digits.      if (n > 9999999999)         return 1;      // initialise dupe flags false.      (i = 0; < 10; i++)         used[i] = 0;      // process digits in number.      while (n != 0) {         // used? return true.          if (used[n%10])  // can cache n%10 if compiler not smart.             return 1;          // otherwise, mark used, go next digit.          used[n%10] = 1;  // , use cached value here.         n /= 10;     }      // no dupes, return false.      return 0; } 

if have limited range of possibilities, can use time-honoured approach of sacrificing space time.

say you're talking of numbers between 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 }; 

and table lookup of hasdupes[n].


based on edit when need handle 9 digits, billion-element array (second solution above) not going possible on calculator :-)

i opt first solution.


Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

sql server - python to mssql encoding problem -

windows - Python Service Installation - "Could not find PythonClass entry" -