How to check if a number is pandigital in Java

1 Answer

0 votes
// A pandigital number is an integer that contains each digit from 0 to 9 
// at least once, with the condition that the leading digit must be nonzero

// for example, 1023456987 is a pandigital number 

import java.util.Arrays;

public class Main {

    public static boolean isPandigitalRange(long num, int start, int end) {
        String str = Long.toString(num);

        // Build the expected digit string
        StringBuilder expected = new StringBuilder();
        for (int i = start; i <= end; i++) {
            expected.append(i);
        }

        // Sort the digits of the number
        char[] digits = str.toCharArray();
        Arrays.sort(digits);
        String sorted = new String(digits);

        return sorted.equals(expected.toString());
    }

    public static boolean isPandigitalRange(long num) {
        return isPandigitalRange(num, 1, 9);
    }

    public static void main(String[] args) {
        System.out.println(isPandigitalRange(123456789));          
        System.out.println(isPandigitalRange(1023456789, 0, 9));   
        System.out.println(isPandigitalRange(987654321));          
        System.out.println(isPandigitalRange(123456780));          
        System.out.println(isPandigitalRange(12345));              
    }
}



/*
run:

true
true
true
false
false

*/

 



answered Dec 30, 2023 by avibootz
edited Feb 25 by avibootz
...