Given a string representing a number, we need to get the sum of all possible sub strings of this string.
Input : s = "6759" Output : 8421 sum = 6 + 7 + 5 + 9 + 67 + 75 + 59 + 675 + 759 + 6759 = 8421 Input : s = "16" Output : 23 sum = 1 + 6 + 16 = 23
We have discussed a solution in below post.
The solution is based on a different approach which does not use any extra space.
This problem can be viewed as follows.
Let number be s = “6759”
1 10 100 1000 6 1 1 1 1 7 2 2 2 5 3 3 9 4
The above table indicates that, when all the substrings are converted further to the ones, tens, hundreds etc.. form, each index of the string will have some fixed occurrence. The 1st index will have 1 occurrence each of ones, tens etc..The 2nd will have 2, 3rd will have 3 and so on.
One more point is that the occurrence of the last element will only be restricted to ones. Last 2nd element will be restricted to ones and tens. last 3rd will be up to a hundred and so on.
From the above points lets find out the sum.
sum = 6*(1*1 + 1*10 + 1*100 + 1*1000) + 7*(2*1 + 2*10 + 2*100) + 5*(3*1 + 3*10) + 9*(4*1) = 6*1*(1111) + 7*2*(111) + 5*3*(11) + 9*4*(1) = 6666 + 1554 + 165 + 36 = 8421
Now, to handle the multiplication we will be having a multiplying factor which starts from 1. It’s clear from the example that the multiplying factor(in reverse) is 1, 11, 111, … and so on. So the multiplication will be based on three factors. number, its index, and a multiplying factor.
This article is contributed by Jatin Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Sum of all substrings of a string representing a number | Set 1
- Replace all occurrences of string AB with C without using extra space
- Remove duplicates from a string in O(1) extra space
- Check if the characters in a string form a Palindrome in O(1) extra space
- To check a number is palindrome or not without using any extra space
- Number of substrings of a string
- Number of substrings of one string present in other
- Number of even substrings in a string of digits
- Number of substrings divisible by 6 in a string of integers
- Number of substrings with odd decimal value in a binary string
- Count the number of vowels occurring in all the substrings of given string
- Repeat substrings of the given String required number of times
- Given a binary string, count number of substrings that start and end with 1.
- Rearrange the string to maximize the number of palindromic substrings
- Dynamic Programming | Wildcard Pattern Matching | Linear Time and Constant Space