Largest number with maximum trailing nines which is less than N and greater than N | It 's better to use var to handle big integers 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
function dig ( a ) { var count = 0 ; while ( a > 0 ) { a /= 10 ; count ++ ; } return count ; } function required_number ( num , n , d ) { var i , j , power = 1 , a , flag = 0 ; for ( i = num ; i >= 1 ; i -- ) { power = Math . pow ( 10 , i ) ; a = n % power ; if ( d > a ) { flag = 1 ; break ; } } if ( flag > 0 ) { var t = 0 ; for ( j = 0 ; j < i ; j ++ ) { t += 9 * Math . pow ( 10 , j ) ; } if ( n % power == t ) document . write ( n ) ; else { document . write ( n - ( n % power ) - 1 ) ; } } else document . write ( n ) ; } var n = 1029 , d = 102 ; var num = dig ( n ) ; required_number ( num , n , d ) ;