Write a program to count number of unique digits in a given number in C/C++.
For example,
Input 12334 Output 3 Explaination Unique Digits in 12334 = { 1, 2, 4 } Input 98000 Output 2 Explaination Unique Digits in 12334 = { 9, 8 }
Logic
First, we read each digit of the given number one by one. We use a hash map to keep track of the number of occurrences of each digit. After iterating all the digits of the input number, we check the number of occurrences of each digit in the hash map. If a digit occurs exactly once, then it is unique. If a digit occurs more than once then it is not unique.
Steps
- Take input from the user. Let it be N.
- Initialize an array of size 10 with all zeros. Let it be hash[]. This array is used to keep track of the occurrences of each digit. hash[0] counts the number of occurrences of 0, hash[1] counts the number of occurrences of 1, and so on.
- Repeat the following step while N is greater than 0.
- Set temp = N % 10. This stores the rightmost digit of N in temp.
- Set N = N / 10. This step removes the rightmost digit of N.
- Increment hash[temp].
- The number of unique characters in the given number is equal to a number of 1 in hash[].
#include<stdio.h>
int count_unique_digits(int n) {
int temp, i;
int count = 0;
int hash[10] = { 0 }; // hash map of size 10 with all zeros
// it keeps track of the number of occurrence of each digit
// reading each digit of n
while (n > 0) {
temp = n % 10; // storing rightmost digit of n in temp
n = n / 10; // removing rightmost digit of n
hash[temp]++;
}
// counting number of 1 in hashmap
for (i = 0; i < 10; ++i) {
if (hash[i] == 1)
count++;
}
return count;
}
int main() {
int n;
printf("Enter a Number: ");
scanf("%d", &n);
printf("Number of Unique Digits: %d", count_unique_digits(n));
}
Output
Enter a Number: 1133226
Number of Unique Digits: 1
Method 2
Instead of using Modulus Operator to read each digit of the given number, we can use itoa() to convert the input number to a string and read each character of the string to count the occurrence of each digit.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int count_unique_digits(int n) {
int i, count = 0;
char str[100];
int hash[10] = { 0 };
// converting n to string and storing the string in str[]
itoa(n, str, 10);
// reading each character of str[]
for (i = 0; i < strlen(str); ++i) {
// we are substracting '0' from str[i]
// to convert character to corresponding integer digit
hash[str[i] - '0']++;
}
// counting number of 1 in hash[]
for (i = 0; i < 10; ++i) {
if (hash[i] == 1)
count++;
}
return count;
}
int main() {
int n;
printf("Enter a Number: ");
scanf("%d", &n);
printf("Number of Unique Digits: %d", count_unique_digits(n));
}
Output
Enter a Number: 123555
Number of Unique Digits: 3
Read