Sum of all substrings of a string representing a number | Set 2 (Constant Extra Space)
Last Updated :
12 Jul, 2022
Given a string representing a number, we need to get the sum of all possible sub strings of this string.
Examples :
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.
Sum of all substrings of a string representing a number | Set 1
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.
Implementation:
C++
// C++ program to print sum of all substring of
// a number represented as a string
#include <bits/stdc++.h>
using namespace std;
// Returns sum of all substring of num
int sumOfSubstrings(string num)
{
long long int sum = 0; // Initialize result
// Here traversing the array in reverse
// order.Initializing loop from last
// element.
// mf is multiplying factor.
long long int mf = 1;
for (int i=num.size()-1; i>=0; i--)
{
// 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.
sum += (num[i]-'0')*(i+1)*mf;
// Making new multiplying factor as
// explained above.
mf = mf*10 + 1;
}
return sum;
}
// Driver code to test above methods
int main()
{
string num = "6759";
cout << sumOfSubstrings(num) << endl;
return 0;
}
Java
// Java program to print sum of all substring of
// a number represented as a string
import java.util.Arrays;
public class GFG {
// Returns sum of all substring of num
public static long sumOfSubstrings(String num)
{
long sum = 0; // Initialize result
// Here traversing the array in reverse
// order.Initializing loop from last
// element.
// mf is multiplying factor.
long mf = 1;
for (int i = num.length() - 1; i >= 0; i --)
{
// 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.
sum += (num.charAt(i) - '0') * (i + 1) * mf;
// Making new multiplying factor as
// explained above.
mf = mf * 10 + 1;
}
return sum;
}
// Driver code to test above methods
public static void main(String[] args)
{
String num = "6759";
System.out.println(sumOfSubstrings(num));
}
}
// This code is contributed by Arnav Kr. Mandal.
Python3
# Python3 program to print sum of all substring of
# a number represented as a string
# Returns sum of all substring of num
def sumOfSubstrings(num):
sum = 0 # Initialize result
# Here traversing the array in reverse
# order.Initializing loop from last
# element.
# mf is multiplying factor.
mf = 1
for i in range(len(num) - 1, -1, -1):
# Each time sum is added to its previous
# sum. Multiplying the three factors as
# explained above.
# int(s[i]) is done to convert char to int.
sum = sum + (int(num[i])) * (i + 1) * mf
# Making new multiplying factor as
# explained above.
mf = mf * 10 + 1
return sum
# Driver code to test above methods
if __name__=='__main__':
num = "6759"
print(sumOfSubstrings(num))
# This code is contributed by
# Sanjit_Prasad
C#
// C# program to print sum of all substring of
// a number represented as a string
using System;
public class GFG {
// Returns sum of all substring of num
public static long sumOfSubstrings(string num)
{
long sum = 0; // Initialize result
// Here traversing the array in reverse
// order.Initializing loop from last
// element.
// mf is multiplying factor.
long mf = 1;
for (int i = num.Length - 1; i >= 0; i --)
{
// 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.
sum += (num[i] - '0') * (i + 1) * mf;
// Making new multiplying factor as
// explained above.
mf = mf * 10 + 1;
}
return sum;
}
// Driver code to test above methods
public static void Main()
{
string num = "6759";
Console.WriteLine(sumOfSubstrings(num));
}
}
// This code is contributed by Sam007.
PHP
<?php
// PHP program to print sum of
// all substring of a number
// represented as a string
// Returns sum of all
// substring of num
function sumOfSubstrings($num)
{
// Initialize result
$sum = 0;
// Here traversing the array
// in reverse order.Initializing
// loop from last element.
// mf is multiplying factor.
$mf = 1;
for ($i = strlen($num) - 1; $i >= 0; $i--)
{
// 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.
$sum += ($num[$i] - '0') * ($i + 1) * $mf;
// Making new multiplying
// factor as explained above.
$mf = $mf * 10 + 1;
}
return $sum;
}
// Driver Code
$num = "6759";
echo sumOfSubstrings($num), "\n";
// This code is contributed by m_kit
?>
JavaScript
<script>
// Javascript program to print sum of all substring of
// a number represented as a string
// Returns sum of all substring of num
function sumOfSubstrings(num)
{
let sum = 0; // Initialize result
// Here traversing the array in reverse
// order.Initializing loop from last
// element.
// mf is multiplying factor.
let mf = 1;
for (let i = num.length - 1; i >= 0; i --)
{
// 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.
sum += (num[i].charCodeAt() - '0'.charCodeAt()) * (i + 1) * mf;
// Making new multiplying factor as
// explained above.
mf = mf * 10 + 1;
}
return sum;
}
let num = "6759";
document.write(sumOfSubstrings(num));
// This code is contributed by rameshtravel07.
</script>
Time Complexity: O(n)
Auxiliary Space: O(1)
Similar Reads
Sum of all substrings of a string representing a number | Set 1
Given an integer represented as a string, we need to get the sum of all possible substrings of this string Examples: Input: num = â1234âOutput: 1670Explanation: Sum = 1 + 2 + 3 + 4 + 12 + 23 +34 + 123 + 234 + 1234 = 1670 Input: num = â421âOutput: 491Explanation: Sum = 4 + 2 + 1 + 42 + 21 + 421 = 491
11 min read
Count number of substrings of a string consisting of same characters
Given a string. The task is to find out the number of substrings consisting of the same characters. Examples: Input: abba Output: 5 The desired substrings are {a}, {b}, {b}, {a}, {bb} Input: bbbcbb Output: 10 Approach: It is known for a string of length n, there are a total of n*(n+1)/2 number of su
6 min read
Count of substrings of a string containing another given string as a substring | Set 2
Given two strings S and T of length N and M respectively, the task is to count the number of substrings of S that contains the string T in it as a substring. Examples: Input: S = âdabcâ, T = âabâOutput: 4Explanation:Substrings of S containing T as a substring are: S[0, 2] = âdabâS[1, 2] = âabâS[1, 3
8 min read
Count of substrings of a string containing another given string as a substring
Given two strings S and T, the task is to count the number of substrings of S that contains string T in it as a substring. Examples: Input: S = "dabc", T = "ab"Output: 4Explanation: Substrings of S containing T as a substring are: S[0, 2] = âdabâS[1, 2] = âabâS[1, 3] = âabcâS[0, 3] = âdabcâ Input: S
8 min read
Count the number of vowels occurring in all the substrings of given string | Set 2
Given a string str[] of length N of lowercase characters containing 0 or more vowels, the task is to find the count of vowels that occurred in all the substrings of the given string. Examples: Input: str = âabcâ Output: 3The given string âabcâ contains only one vowel = âaâ Substrings of âabcâ are =
5 min read
Number of substrings of one string present in other
Suppose we are given a string s1, we need to the find total number of substring(including multiple occurrences of the same substring) of s1 which are present in string s2. Examples: Input : s1 = aab s2 = aaaab Output :6 Substrings of s1 are ["a", "a", "b", "aa", "ab", "aab"]. These all are present i
4 min read
Repeat substrings of the given String required number of times | Set 2 (Recursion)
Given string str, the task is to repeat every substring of the string X number of times where X is the number composed of the consecutive digits present just after the substring in the original string. For example, if str = âg1e2ks1â then the resultant string will be âgeeksâ. Examples: Input: str =
7 min read
Sum of all possible strings obtained by removal of non-empty substrings
Given numerical string str consisting of N integers, the task is to find the sum of all possible resulting strings after removing non-empty substrings. Examples: Input: str = "205"Output: 57Explanation: Substrings that can be removed are "2", "0", "5", "20", "05", "205". The resultant strings are "0
8 min read
Calculate sum of all numbers present in a string
Given a string S containing alphanumeric characters, The task is to calculate the sum of all numbers present in the string. Examples: Input: 1abc23Output: 24Explanation: 1 + 23 = 24 Input: geeks4geeksOutput: 4 Input: 1abc2x30yz67Output: 100 Recommended PracticeSum of numbers in stringTry It!Approach
13 min read
Number of substrings divisible by 6 in a string of integers
Given a string consisting of integers 0 to 9. The task is to count the number of substrings which when convert into integer are divisible by 6. Substring does not contain leading zeroes. Examples: Input : s = "606". Output : 5 Substrings "6", "0", "6", "60", "606" are divisible by 6. Input : s = "48
9 min read