-6

This is a code that counts the number of digits in a number recursively. What can I add to this code to count how many different digits are in a number? Or maybe there is some other way?

    int numberOfDigits(int n)
    {
    if(n==0)
    return 0;
    else
    return numberOfDigits(n/10)+1;
    }
arani
  • 13
  • 7

1 Answers1

2

Use sets!

static int NumberOfDigits(int a) {
    return new HashSet<char>(Math.Abs(a).ToString()).Count;
}

We make a into a string and then turn the string into a set of characters. Since sets cannot contain duplicate values, the count of the set is the number of distinct digits.

Sweeper
  • 213,210
  • 22
  • 193
  • 313