Home > Enterprise >  Why am I not able to print output as number of unique digits between range n1 to n2?
Why am I not able to print output as number of unique digits between range n1 to n2?

Time:10-05

Given two non-negative integers n1 and n2, where n1<n2. The task is to find the total number of integers in the range [n1, n2](both inclusive) which have no repeated digits.

I have worked out the logic but the output is still not right.

int main(void) {

  int n1, n2, count = 0, num;
  scanf("%d %d", & n1, & n2);

  for (int i = n1; i <= n2; i  ) {
    int num = i;
    bool m[10] = {
      false
    };
    while (num > 0) {
      if (m[num % 10] == true) {
        break;
        m[num % 10] = true;
        num = num / 10;
      }

    }
  }
  if (num == 0) {
    count  ;
  }
  printf("%d", count);
  return 0;
}

CodePudding user response:

It is very hard to read your code. You need to indent it properly - it will help you a lot.

  1. Use functions.
  2. Not always bool is the best choice.
int hasRepeating(long long num)
{
    int dig[10] = {0,};

    do
    {
        if(  dig[abs((int)(num % 10))] > 1) return 1;
        num /= 10;
    }while(num);
    return 0;
}

size_t findNumber(long long num1, long long num2)
{
    size_t num = 0;
    for(long long x = num1; x <= num2; x  )
    {
        if(!hasRepeating(x)) num  ;
    }
    return num;
}

int main(void)
{
    int num1 = -9000, num2 = 100000;
    printf("Number of numbers with not repeated digits in range <%d, %d> = %zu\n", num1, num2, findNumber(num1, num2));
}
  •  Tags:  
  • c
  • Related