The aim is to find the total count of numbers with unique digits in a given range using C# Language.
Approach
We divide this problem into 3 parts,
- Traversing the range
- Checking the Number
- Returning the Count
Traversing the Range
We traverse the given range using any loop, for, while or do..while. Here I used for loop.
This is done to check all the possible numbers within a given range.
Checking the Number
For each number we check whether the digits are unique or not. For my solution I used Generic List from System.Collections.Generic to create a List that stores the digits a given number. I sorted the List to using Sort() method. The function CheckDigits() check each number by traversing this sorted list and returning a boolean value false if any of the consecutive digits of the List are same. If not this means all the digits in the List are Unique.
Returning the Count
Now the Unique function checks for every number in the given rabge, whether its unique or not. If the CheckDigits() function returns true, which means that the digits are unique, the count is incremented. At the end the count is returned to the main function and the output is displayed on the main screen.
- using System;
- using System.Collections.Generic;
- using System.Linq;
-
- public class Program{
- public static void Main(){
- //Getting the Upper Limit and Lower Limit Range
- int ll = Int32.Parse(Console.ReadLine());
- int ul = Int32.Parse(Console.ReadLine());
-
- int output = Unique(ll,ul);
- Console.WriteLine(output);
- }
-
- public static int Unique(int ll,int ul){
- int c = 0;
- for(int i=ll;i<=ul;i++){
- bool f = CheckDigits(i);
- if(f==true){
- c=c+1;
- }
- }
- //Returning Count
- return c;
- }
-
- static bool CheckDigits(int i){
- List<int> d = new List<int>();
- while(i>0){
- int temp = i%10;
- d.Add(temp);
- i = i/10;
- }
-
- //Sorting to make sure repetitive digits are consecutive.
- d.Sort();
-
- //Make sure to run the loop for 1 less than the size of List else it would throw System.Out.Of.Bounds Error
- for(int j=0;j<d.Count()-1;j++){
- if(d[j]==d[j+1]){
- return false;
- }
- }
-
- return true;
- }
- }
There are many methods to solve this problem. This is one of the approaches using List. Do share your unique way of solving this problem!