Count of Numbers in Range where first digit is equal to last digit of the number in C++

C++Server Side ProgrammingProgramming

Given a range of numbers between start and end. The goal is to find the count of numbers that have the first digit equal to the last digit and fall in the range [ first,last ].

All single digit numbers will be counted if they lie in the range.

Let us understand with examples.

For Example

Input - start = 100, end = 200

Output - Count of Numbers in Range where first digit is equal to last digit of the number are: 10

Explanation -  The numbers will be:

101, 121, 131, 141, 151, 161, 171, 181 and 191.

Input - start = 1, end = 10

Output - Count of Numbers in Range where first digit is equal to last digit of the number are: 9

Explanation - All 1-digit numbers will be counted. 1, 2, 3, 4, 5, 6, 7, 8, 9

Approach used in the below program is as follows

All single digit numbers if they lie in the range [start,end] will be counted. Now for each number check first and last digits. If the first digit is greater than the last then add 8 + val/10 to count, if smaller then add 9 + val/10 to the count. Here val is the current number in the recursive call to range(int val).

  • Take integers start and end as range variables.
  • Set count = range(end) - range(start).
  • Function range(int val) takes integer numbers and returns the count of numbers in Range where the first digit is equal to the last digit of the number.
  • Take the initial count as 0.
  • Take the end as the last digit which is val%10.
  • Return val if it is a single digit number ( less than 10 ).
  • Now using while loop calculate as start=val%10. Reduce val by 10. So the start will have the first digit in it.
  • Now if start<=end then add 9 + set_val / 10 to count.
  • Now if start>end then add 8 + set_val / 10 to count.
  • At the end return count as result.

Example

Live Demo

#include <iostream>
using namespace std;

int range(int val) {
   int count = 0;
   int start;
   int end = val % 10;
   int set_val = val;

   if (val < 10) {
      return val;
   }
   end = val % 10;
   while (val) {
      start = val % 10;
      val = val / 10;
   }
   if (start <= end) {
      count = 9 + set_val / 10;
   } else {
      count = 8 + set_val / 10;
   }
   return count;
}
int main() {
   int start = 10, end = 50;
   int count = range(end) - range(start);
   cout << "Count of Numbers in Range where first digit is equal to last digit of the number are: " << count;
   return 0;
}

If we run the above code it will generate the following output 

Output

Count of Numbers in Range where first digit is equal to last digit of the number are: 4

raja
Published on 29-Jan-2021 08:06:41
Advertisements