w3resource

C Programming: Count unique digits of integers

C Programming Mathematics: Exercise-37 with Solution

Write a C program that counts the number of integers whose digits are unique from 1 and a given integer value.

Example:
Input: n = 30
From 1 to 30 all the integers have unique digits, except 11 and 22
Output: 28

Test Data:
(30) -> 28
(135) -> 110

Sample Solution:

C Code:

#include <stdio.h>
#include <math.h>

int test(int n) {
  //Length of an integer
  int len = floor(log10(abs(n))) + 1;
  int temp, i;
  int count = 0;
  int data[10] = {
    0
  };
  while (n > 0) {
    temp = n % 10;
    n = n / 10;
    data[temp]++;
  }
  for (i = 0; i < 10; ++i) {
    if (data[i] == 1)
      count++;
  }
  if (count == len)
    return len;
  else
    return 0;
}
int main(void) {
  int n = 135, ctr = 0, result;
  for (int i = 1; i <= n; i++) {
    result = test(i);
    if (result > 0) {
      //printf("\ni = %d, result = %d",i,result);
      ctr++;
      result = 0;
    }
  }
  printf("Unique digits of integers from 1 and %d = %d", n, ctr);
}


Sample Output:

Unique digits of integers from 1 and 135 = 110

Flowchart:

Flowchart: Count unique digits of integers

C Programming Code Editor:

Improve this sample solution and post your code through Disqus.

Previous: Count common factors of two integers.
Next: Count Integers with Odd digit sum.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

What's the point of const pointers?

const is a tool which you should use in pursuit of a very important C++ concept:

Find bugs at compile-time, rather than run-time, by getting the compiler to enforce what you mean.

Even though it does not change the functionality, adding const generates a compiler error when you're doing things you didn't mean to do. Imagine the following typo:

void foo(int* ptr)
{
    ptr = 0;// oops, I meant *ptr = 0
}

If you use int* const, this would generate a compiler error because you're changing the value to ptr. Adding restrictions via syntax is a good thing in general. Just don't take it too far -- the example you gave is a case where most people don't bother using const.

Ref : https://bit.ly/33Cdn3Q