Count numbers with same first and last digits in C++

C++Server Side ProgrammingProgramming

We are given an interval [first, last]. The goal is to find the count of numbers that have the same first and last digit within this interval. For example, 232 has the same first and last digit as 2.

We will do this by traversing from i=first to i=last. For each number I compare its first digit with the last digit, if they are the same increment the count.

Let’s understand with examples.

Input − first=8 last=40

Output − Count of numbers with same first and last digits − 5

Explanation − Numbers between 8 and 40 with same first and last digit −

8, 9, 11, 22, 33

Input − first=100 last=200

Output − Count of numbers with same first and last digits: 5

Explanation − Numbers between 100 and 200 with same first and last digit −

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

Approach used in the below program is as follows

  • We take two integers first and last to define range [first,last].

  • Function getFirstDigit(int num) takes a number and returns its first digit.

  • While num>=10, divide num by 10. In the end num will have the first digit. Return this value.

  • Function getCount(int fst,int lst) takes range variables and returns the count of numbers with the same first and last digits.

  • Take the initial count as 0.

  • Using for loop start from i=fst to i=lst, for each i calculate it first digit by calling getFirstDigit(i) and store in fdigit. (fdigit=getFirstDigit(i)).

  • Calculate last digit as ldigit=i%10.

  • If ldigit==fdigit, means they are the same. Increment count.

  • Return count as result.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
//to find starting digit
int getFirstDigit(int num){
   while (num >= 10)
      { num = num/ 10; }
   return num;
}
int getCount(int fst,int lst){
   int count=0;
   for(int i=fst;i<=lst;i++){
      int fdigit=getFirstDigit(i);
      int ldigit=i%10; //to get last digit
      if(fdigit==ldigit) //if both are equal increment count
         { ++count; }
   }
   return count;
}
int main(){
   int first = 10, last = 23;
   cout<<"Numbers with same first and last digits:"<<getCount(first, last);
   return 0;
}

Output

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

Numbers with same first and last digits:2
raja
Published on 29-Aug-2020 11:56:44
Advertisements