Sum of all substrings of a string representing a number | Set 2 ( Constant Extra Space ) | Returns sum of all substring of num ; Initialize result ; Here traversing the array in reverse order . Initializing loop from last element . mf is multiplying factor . ; Each time sum is added to its previous sum . Multiplying the three factors as explained above . s [ i ] - '0' is done to convert char to int . ; Making new multiplying factor as explained above . ; Driver Code
< ? php function sumOfSubstrings ( $ num ) { $ sum = 0 ; $ mf = 1 ; for ( $ i = strlen ( $ num ) - 1 ; $ i >= 0 ; $ i -- ) { $ sum += ( $ num [ $ i ] - '0' ) * ( $ i + 1 ) * $ mf ; $ mf = $ mf * 10 + 1 ; } return $ sum ; } $ num = "6759" ; echo sumOfSubstrings ( $ num ) , " STRNEWLINE " ; ? >