Largest number N which can be reduced to 0 in K steps | Utility function to return the first digit of a number . ; Remove last digit from number till only one digit is left ; return the first digit ; Utility function that returns the count of numbers written down when starting from n ; Function to find the largest number N which can be reduced to 0 in K steps ; Get the sequence length of the mid point ; Until k sequence length is reached ; Update mid point ; Get count of the new mid point ; Update right to mid ; Update left to mid ; Increment mid point by one while count is equal to k to get the maximum value of mid point ; Driver Code
< ? php function firstDigit ( $ n ) { while ( $ n >= 10 ) { $ n = ( int ) ( $ n / 10 ) ; } return $ n ; } function getCount ( $ n ) { $ count = 1 ; while ( $ n != 0 ) { $ leadDigit = firstDigit ( $ n ) ; $ n -= $ leadDigit ; $ count ++ ; } return $ count ; } function getLargestNumber ( $ k ) { $ left = $ k ; $ right = $ k * 10 ; $ mid = ( int ) ( ( $ left + $ right ) / 2 ) ; $ len = getCount ( $ mid ) ; while ( $ len != $ k ) { $ mid = ( int ) ( ( $ left + $ right ) / 2 ) ; $ len = getCount ( $ mid ) ; if ( $ len > $ k ) { $ right = $ mid ; } else { $ left = $ mid ; } } while ( $ len == $ k ) { if ( $ len != getCount ( $ mid + 1 ) ) { break ; } $ mid ++ ; } return ( $ mid ) ; } $ k = 3 ; echo ( getLargestNumber ( $ k ) ) ; ? >