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.
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
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).
#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
Count of Numbers in Range where first digit is equal to last digit of the number are: 4