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