Search code examples
c#countdigits

Is it possible to count the number of different digits in a number recursively?


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 it has to be done some other way?

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

Solution

  • 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.