Sunday, November 17, 2024
Google search engine
HomeData Modelling & AISum of all substrings of a string representing a number | Set...

Sum of all substrings of a string representing a number | Set 2 (Constant Extra Space)

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>


Output

8421

Time Complexity: O(n)
Auxiliary Space: O(1)

This article is contributed by Jatin Goyal. If you like neveropen and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the neveropen main page and help other Geeks. 

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments