Find the occurrences of digit d in the range [ 0. . n ] | PHP program to count appearances of a digit ' d ' in range from [ 0. . n ] ; Initialize result ; Count appearances in numbers starting from d . ; When the last digit is equal to d ; When the first digit is equal to d then ; increment result as well as number ; In case of reverse of number such as 12 and 21 ; Driver code
< ? php function getOccurence ( $ n , $ d ) { $ result = 0 ; $ itr = $ d ; while ( $ itr <= $ n ) { if ( $ itr % 10 == $ d ) $ result ++ ; if ( $ itr != 0 && floor ( $ itr / 10 ) == $ d ) { $ result ++ ; $ itr ++ ; } else if ( floor ( $ itr / 10 ) == $ d - 1 ) $ itr = $ itr + ( 10 - $ d ) ; else $ itr = $ itr + 10 ; } return $ result ; } $ n = 11 ; $ d = 1 ; echo getOccurence ( $ n , $ d ) ; ? >