Count numbers with same first and last digits | 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
function getFirstDigit ( x ) { while ( x >= 10 ) x /= 10 ; return x ; } function getCountWithSameStartAndEndFrom1 ( x ) { if ( x < 10 ) return x ; let tens = x / 10 ; let res = tens + 9 ; let firstDigit = getFirstDigit ( x ) ; let lastDigit = x % 10 ; if ( lastDigit < firstDigit ) res -- ; return res ; } function getCountWithSameStartAndEnd ( start , end ) { return getCountWithSameStartAndEndFrom1 ( end ) - getCountWithSameStartAndEndFrom1 ( start - 1 ) ; } let start = 5 , end = 40 ; document . write ( getCountWithSameStartAndEnd ( start , end ) ) ;