How to check if every digit in a number appears only once in C

1 Answer

0 votes
#include <stdio.h>

// n % 10 extracts the last digit.
// 1 << digit creates a bitmask for that digit.
// mask & bit checks whether the bit for this digit is already set.
// Mark the digit as seen: mask |= bit; This sets the bit for the current digit.

int allDigitsUnique(int n) {
    int mask = 0;

    while (n > 0) {
        int digit = n % 10;
        int bit = 1 << digit;

        if (mask & bit)
            return 0;   // false: digit already seen

        mask |= bit;
        n /= 10;
    }
    
    return 1;   // true
}

int main(void) {
    int n = 123456;
    printf("%s\n", allDigitsUnique(n) ? "Unique" : "Not unique");

    n = 123452;
    printf("%s\n", allDigitsUnique(n) ? "Unique" : "Not unique");

    return 0;
}



/*
run:

Unique
Not unique

*/

 



answered Feb 25 by avibootz
edited Feb 25 by avibootz
...