Sum of all substrings of a string representing a number | Set 1 | Method to convert character digit to integer digit ; Returns sum of all substring of num ; allocate memory equal to length of string ; initialize first value with first digit ; loop over all digits of string ; update each sumofdigit from previous value ; add current value to the result ; Driver Code
< ? php function toDigit ( $ ch ) { return ( $ ch - '0' ) ; } function sumOfSubstrings ( $ num ) { $ n = strlen ( $ num ) ; $ sumofdigit [ $ n ] = 0 ; $ sumofdigit [ 0 ] = toDigit ( $ num [ 0 ] ) ; $ res = $ sumofdigit [ 0 ] ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) { $ numi = toDigit ( $ num [ $ i ] ) ; $ sumofdigit [ $ i ] = ( $ i + 1 ) * $ numi + 10 * $ sumofdigit [ $ i - 1 ] ; $ res += $ sumofdigit [ $ i ] ; } return $ res ; } $ num = "1234" ; echo sumOfSubstrings ( $ num ) ; ? >