Fastest algorithm to check if a number is pandigital?

Posted by medopal on Stack Overflow See other posts from Stack Overflow or by medopal
Published on 2010-03-20T21:43:45Z Indexed on 2010/03/20 21:51 UTC
Read the original article Hit count: 173

Filed under:
|
|
|

Pandigital number is a number that contains the digits 1..number length.
For example 123, 4312 and 967412385.

I have solved many Project Euler problems, but the Pandigital problems always exceed the one minute rule.

This is my pandigital function:

private boolean isPandigital(int n){
    Set<Character> set= new TreeSet<Character>();   
    String string = n+"";
    for (char c:string.toCharArray()){
        if (c=='0') return false;
        set.add(c);
    }
    return set.size()==string.length();
}

Create your own function and test it with this method

int pans=0;
for (int i=123456789;i<=123987654;i++){
    if (isPandigital(i)){
         pans++;
    }
}

Using this loop, you should get 720 pandigital numbers. My average time was 500 millisecond.

I'm using Java, but the question is open to any language.

© Stack Overflow or respective owner

Related posts about challenge

Related posts about fun