Append a digit in the end to make the number equal to the length of the remaining string | C ++ implementation of the approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int find_digit ( string s , int n ) { int first_digit = -1 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( s [ i ] < '0' s [ i ] > '9' ) { first_digit = i ; break ; } } first_digit ++ ; int s_len = first_digit ; int num = 0 , pw = 1 ; int i = n - 1 ; while ( i >= 0 ) { if ( s [ i ] >= '0' && s [ i ] <= '9' ) { int digit = s [ i ] - '0' ; num = num + ( pw * digit ) ; if ( num >= s_len ) return -1 ; pw = pw * 10 ; } i -- ; } num = num * 10 ; int req = s_len - num ; if ( req > 9 req < 0 ) return -1 ; return req ; } int main ( ) { string s = " abcd0" ; int n = s . length ( ) ; cout << find_digit ( s , n ) ; return 0 ; }