Count numbers with same first and last digits | C ++ program to get count of numbers with same start and end digit in an interval ; Utility method to get first digit of x ; method to return count of numbers with same starting and ending digit from 1 upto x ; get ten - spans from 1 to x ; add 9 to consider all 1 digit numbers ; Find first and last digits ; If last digit is greater than first digit then decrease count by 1 ; Method to return count of numbers with same starting and ending digit between start and end ; Driver code to test above methods
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getFirstDigit ( int x ) { while ( x >= 10 ) x /= 10 ; return x ; } int getCountWithSameStartAndEndFrom1 ( int x ) { if ( x < 10 ) return x ; int tens = x / 10 ; int res = tens + 9 ; int firstDigit = getFirstDigit ( x ) ; int lastDigit = x % 10 ; if ( lastDigit < firstDigit ) res -- ; return res ; } int getCountWithSameStartAndEnd ( int start , int end ) { return getCountWithSameStartAndEndFrom1 ( end ) - getCountWithSameStartAndEndFrom1 ( start - 1 ) ; } int main ( ) { int start = 5 , end = 40 ; cout << getCountWithSameStartAndEnd ( start , end ) ; return 0 ; }