Append a digit in the end to make the number equal to the length of the remaining string | Function to return the required digit ; To store the position of the first numeric digit in the string ; To store the length of the string without the numeric digits in the end ; pw stores the current power of 10 and num is to store the number which is appended in the end ; If current character is a numeric digit ; Get the current digit ; Build the number ; If number exceeds the length ; Next power of 10 ; Append 0 in the end ; Required number that must be added ; If number is not a single digit ; Driver code
function find_digit ( s , n ) { var first_digit = - 1 ; for ( var i = n - 1 ; i >= 0 ; i -- ) { if ( s [ i ] < ' ' s [ i ] > ' ' ) { first_digit = i ; break ; } } first_digit ++ ; var s_len = first_digit ; var num = 0 , pw = 1 ; var i = n - 1 ; while ( i >= 0 ) { if ( s [ i ] >= ' ' && s [ i ] <= ' ' ) { var digit = s [ i ] - ' ' ; num = num + ( pw * digit ) ; if ( num >= s_len ) return - 1 ; pw = pw * 10 ; } i -- ; } num = num * 10 ; var req = s_len - num ; if ( req > 9 req < 0 ) return - 1 ; return req ; } var s = " " ; var n = s . length ; document . write ( find_digit ( s , n ) ) ;