How to check if a number is pandigital in C

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 

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int isPandigitalRange(long long num, int start, int end) {
    char str[32];
    sprintf(str, "%lld", num);

    // Build the expected digit string
    char expected[32] = "";
    for (int i = start; i <= end; i++) {
        char c = '0' + i;
        strncat(expected, &c, 1);
    }

    // Sort digits of the number
    int len = strlen(str);
    char digits[32];
    strcpy(digits, str);

    // Simple bubble sort
    for (int i = 0; i < len - 1; i++) {
        for (int j = i + 1; j < len; j++) {
            if (digits[j] < digits[i]) {
                char temp = digits[i];
                digits[i] = digits[j];
                digits[j] = temp;
            }
        }
    }

    return strcmp(digits, expected) == 0;
}

int main() {
    printf("%s\n", isPandigitalRange(123456789, 1, 9) ? "true" : "false");
    printf("%s\n", isPandigitalRange(1023456789, 0, 9) ? "true" : "false");
    printf("%s\n", isPandigitalRange(987654321, 1, 9) ? "true" : "false");
    printf("%s\n", isPandigitalRange(123456780, 1, 9) ? "true" : "false");
    printf("%s\n", isPandigitalRange(123456780, 1, 9) ? "true" : "false");
    printf("%s\n", isPandigitalRange(123455789, 1, 9) ? "true" : "false");
    printf("%s\n", isPandigitalRange(12345, 1, 9) ? "true" : "false");

    return 0;
}



/*
run:

true
true
true
false
false
false
false

*/

 



answered Feb 25 by avibootz
...