Largest number with maximum trailing nines which is less than N and greater than N | function to count no of digits ; function to implement above approach ; if difference between power and n doesn 't exceed d ; loop to build a number from the appropriate no of digits containing only 9 ; if the build number is same as original number ( n ) ; observation ; Driver Code ; variable that stores no of digits in n
< ? php function dig ( $ a ) { $ count = 0 ; while ( $ a > 0 ) { $ a = ( int ) ( $ a / 10 ) ; $ count ++ ; } return $ count ; } function required_number ( $ num , $ n , $ d ) { $ flag = 0 ; for ( $ i = $ num ; $ i >= 1 ; $ i -- ) { $ power = pow ( 10 , $ i ) ; $ a = $ n % $ power ; if ( $ d > $ a ) { $ flag = 1 ; break ; } } if ( $ flag ) { $ t = 0 ; for ( $ j = 0 ; $ j < $ i ; $ j ++ ) { $ t += 9 * pow ( 10 , $ j ) ; } if ( $ n % $ power == $ t ) echo $ n ; else { echo ( $ n - ( $ n % $ power ) - 1 ) ; } } else echo $ n ; } $ n = 1029 ; $ d = 102 ; $ num = dig ( $ n ) ; required_number ( $ num , $ n , $ d ) ; ? >