Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Sum of all substrings of a string representing a number | Set 1
Next article icon

Sum of all prefixes of given numeric string

Last Updated : 08 Mar, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given string str having N characters representing an integer, the task is to calculate the sum of all possible prefixes of the given string.

Example:

Input: str = "1225"
Output: 1360
Explanation: The prefixes of the given string are 1, 12, 122, and 1225 and their sum will be 1 + 12 + 122 + 1225 = 1360.

Input: str = "20"
Output: 22

Approach: The given problem is an implementation-based problem and can be solved by iterating over all the prefixes of the string and maintaining their sum in a string. The sum of two integers represented as strings can be done using the approach discussed here.

Below is the implementation of the above approach:

C++
// C++ program of the above approach #include <bits/stdc++.h> using namespace std;  // Function for finding sum of larger numbers string findSum(string str1, string str2) {     // Before proceeding further, make     // sure length of str2 is larger     if (str1.length() > str2.length())         swap(str1, str2);      // Stores resulting sum     string str = "";      // Calculate length of both string     int n1 = str1.length(), n2 = str2.length();      // Reverse both of strings     reverse(str1.begin(), str1.end());     reverse(str2.begin(), str2.end());      int carry = 0;     for (int i = 0; i < n1; i++) {         // Compute sum of current         // digits and carry         int sum             = ((str1[i] - '0')                + (str2[i] - '0')                + carry);         str.push_back(sum % 10 + '0');          // Carry for next step         carry = sum / 10;     }      // Add remaining digits     for (int i = n1; i < n2; i++) {         int sum = ((str2[i] - '0') + carry);         str.push_back(sum % 10 + '0');         carry = sum / 10;     }      // Add remaining carry     if (carry)         str.push_back(carry + '0');      // Reverse string     reverse(str.begin(), str.end());      // Return Answer     return str; }  // Function to find sum of all prefixes // of a string representing a number string sumPrefix(string str) {     // Stores the desired sum     string sum = "0";      // Stores the current prefix     string curPre = "";      // Loop to iterate str     for (int i = 0; i < str.length(); i++) {         // Update current prefix         curPre += str[i];          // Update Sum         sum = findSum(curPre, sum);     }      // Return Answer     return sum; }  // Driver Code int main() {     string str = "1225";     cout << sumPrefix(str);      return 0; } 
Java
// Java program of the above approach import java.util.*; class GFG{  // Function for finding sum of larger numbers static String findSum(String str1, String str2) {        // Before proceeding further, make     // sure length of str2 is larger     if (str1.length() > str2.length()) {         String s = str1;         str1=str2;         str2=s;     }      // Stores resulting sum     String str = "";      // Calculate length of both String     int n1 = str1.length(), n2 = str2.length();      // Reverse both of Strings     str1 = reverse(str1);     str2 = reverse(str2);      int carry = 0;     for (int i = 0; i < n1; i++) {         // Compute sum of current         // digits and carry         int sum             = ((str1.charAt(i) - '0')                + (str2.charAt(i) - '0')                + carry);         str+=(char)((sum % 10 + '0'));          // Carry for next step         carry = sum / 10;     }      // Add remaining digits     for (int i = n1; i < n2; i++) {         int sum = ((str2.charAt(i) - '0') + carry);         str+=(char)(sum % 10 + '0');         carry = sum / 10;     }      // Add remaining carry     if (carry > 0)         str += (carry + '0');      // Reverse String     str = reverse(str);      // Return Answer     return str; }  // Function to find sum of all prefixes // of a String representing a number static String sumPrefix(String str) {        // Stores the desired sum     String sum = "0";      // Stores the current prefix     String curPre = "";      // Loop to iterate str     for (int i = 0; i < str.length(); i++)     {                // Update current prefix         curPre += (char)(str.charAt(i));          // Update Sum         sum = findSum(curPre, sum);     }      // Return Answer     return sum; } static String reverse(String input) {     char[] a = input.toCharArray();     int l, r = a.length - 1;     for (l = 0; l < r; l++, r--) {         char temp = a[l];         a[l] = a[r];         a[r] = temp;     }     return String.valueOf(a); }    // Driver Code public static void main(String[] args) {     String str = "1225";     System.out.print(sumPrefix(str)); } }  // This code is contributed by shikhasingrajput  
Python3
# Python code for the above approach  # Function for finding sum of larger numbers def findSum(str1, str2):      # Before proceeding further, make     # sure length of str2 is larger     if (len(str1) > len(str2)):         temp = str1;         str1 = str2;         str2 = temp;      # Stores resulting sum     str = [];      # Calculate length of both string     n1 = len(str1)     n2 = len(str2)      # Reverse both of strings     str1 = list(str1)     str2 = list(str2)     str1.reverse();     str2.reverse();      carry = 0;     for i in range(n1):                # Compute sum of current         # digits and carry         sum = ((ord(str1[i]) - ord('0')) + (ord(str2[i]) - ord('0')) + carry);         str.append(chr(sum % 10 + ord('0')));          # Carry for next step         carry = sum // 10      # Add remaining digits     for i in range(n1, n2):         sum = ((ord(str2[i]) - ord('0')) + carry);         str.append(chr(sum % 10 + ord('0')));         carry = sum // 10      # Add remaining carry     if (carry):         str.append(chr(carry + ord('0')));      # Reverse string     str.reverse();      # Return Answer     return ''.join(str)  # Function to find sum of all prefixes # of a string representing a number def sumPrefix(str):      # Stores the desired sum     sum = "0";      # Stores the current prefix     curPre = "";      # Loop to iterate str     for i in range(len(str)):         # Update current prefix         curPre += str[i];          # Update Sum         sum = findSum(curPre, sum);          # Return Answer     return sum;  # Driver Code str = "1225"; print(sumPrefix(str));  # This code is contributed by Saurabh Jaiswal 
C#
// C# program of the above approach using System;  public class GFG{  // Function for finding sum of larger numbers static String findSum(String str1, String str2) {        // Before proceeding further, make     // sure length of str2 is larger     if (str1.Length > str2.Length) {         String s = str1;         str1=str2;         str2=s;     }      // Stores resulting sum     String str = "";      // Calculate length of both String     int n1 = str1.Length, n2 = str2.Length;      // Reverse both of Strings     str1 = reverse(str1);     str2 = reverse(str2);      int carry = 0;     for (int i = 0; i < n1; i++)      {                // Compute sum of current         // digits and carry         int sum             = ((str1[i] - '0')                + (str2[i] - '0')                + carry);         str+=(char)((sum % 10 + '0'));          // Carry for next step         carry = sum / 10;     }      // Add remaining digits     for (int i = n1; i < n2; i++) {         int sum = ((str2[i] - '0') + carry);         str+=(char)(sum % 10 + '0');         carry = sum / 10;     }      // Add remaining carry     if (carry > 0)         str += (carry + '0');      // Reverse String     str = reverse(str);      // Return Answer     return str; }  // Function to find sum of all prefixes // of a String representing a number static String sumPrefix(String str) {        // Stores the desired sum     String sum = "0";      // Stores the current prefix     String curPre = "";      // Loop to iterate str     for (int i = 0; i < str.Length; i++)     {                // Update current prefix         curPre += (char)(str[i]);          // Update Sum         sum = findSum(curPre, sum);     }      // Return Answer     return sum; } static String reverse(String input) {     char[] a = input.ToCharArray();     int l, r = a.Length - 1;     for (l = 0; l < r; l++, r--) {         char temp = a[l];         a[l] = a[r];         a[r] = temp;     }     return String.Join("",a); }    // Driver Code public static void Main(String[] args) {     String str = "1225";     Console.Write(sumPrefix(str)); } }  // This code is contributed by 29AjayKumar  
JavaScript
<script>         // JavaScript code for the above approach          // Function for finding sum of larger numbers         function findSum(str1, str2)         {                      // Before proceeding further, make             // sure length of str2 is larger             if (str1.length > str2.length) {                 let temp = str1;                 str1 = str2;                 str2 = temp;             }              // Stores resulting sum             let str = [];              // Calculate length of both string             let n1 = str1.length, n2 = str2.length;              // Reverse both of strings             str1 = str1.split('')             str2 = str2.split('')             str1.reverse();             str2.reverse();              let carry = 0;             for (let i = 0; i < n1; i++) {                 // Compute sum of current                 // digits and carry                 let sum                     = ((str1[i].charCodeAt(0) - '0'.charCodeAt(0))                         + (str2[i].charCodeAt(0) - '0'.charCodeAt(0))                         + carry);                 str.push(String.fromCharCode(sum % 10 + '0'.charCodeAt(0)));                  // Carry for next step                 carry = Math.floor(sum / 10);             }              // Add remaining digits             for (let i = n1; i < n2; i++) {                 let sum = ((str2[i].charCodeAt(0) - '0'.charCodeAt(0)) + carry);                 str.push(String.fromCharCode(sum % 10 + '0'.charCodeAt(0)));                 carry = Math.floor(sum / 10);             }              // Add remaining carry             if (carry)                 str.push(String.fromCharCode(carry + '0'.charCodeAt(0)));              // Reverse string             str.reverse();              // Return Answer             return str.join('');         }          // Function to find sum of all prefixes         // of a string representing a number         function sumPrefix(str)          {                      // Stores the desired sum             let sum = "0";              // Stores the current prefix             let curPre = "";              // Loop to iterate str             for (let i = 0; i < str.length; i++) {                 // Update current prefix                 curPre += str[i];                  // Update Sum                 sum = findSum(curPre, sum);             }              // Return Answer             return sum;         }          // Driver Code         let str = "1225";         document.write(sumPrefix(str));         // This code is contributed by Potta Lokesh     </script> 

 
 


Output
1360


 

Time Complexity: O(N2)
Auxiliary Space: O(N)


 


Next Article
Sum of all substrings of a string representing a number | Set 1

A

arunbang17
Improve
Article Tags :
  • Misc
  • Strings
  • Mathematical
  • DSA
  • prefix
Practice Tags :
  • Mathematical
  • Misc
  • Strings

Similar Reads

  • 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
  • Length of all prefixes that are also the suffixes of given string
    Given a string S consisting of N characters, the task is to find the length of all prefixes of the given string S that are also suffixes of the same string S. Examples: Input: S = "ababababab"Output: 2 4 6 8Explanation: The prefixes of S that are also its suffixes are: "ab" of length = 2"abab" of le
    10 min read
  • Number of even substrings in a string of digits
    Given a string of digits 0 - 9. The task is to count a number of substrings which when converting into integer form an even number. Examples : Input : str = "1234".Output : 6"2", "4", "12", "34", "234", "1234" are 6 substring which are even.Input : str = "154".Output : 3Input : str = "15".Output : 0
    9 min read
  • Find the final String by incrementing prefixes of given length
    Given a string S and an array roll[] where roll[i] represents incrementing first roll[i] characters in the string, the task is to increment all the prefixes mentioned in the array and find the final string. Note: Incrementing means increasing the ASCII value of the character, like incrementing ‘z’ w
    7 min read
  • 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
  • Check if a given string is sum-string
    Given a string of digits, determine whether it is a ‘sum-string’. A string S is called a sum-string if the rightmost substring can be written as the sum of two substrings before it and the same is recursively true for substrings before it. Examples: “12243660” is a sum string. Explanation : 24 + 36
    12 min read
  • Sum of two large numbers as Strings
    Given two numbers as strings. The numbers may be very large (may not fit in long long int), the task is to find sum of these two numbers. Examples: Input: s1 = "23", s2 = "25"Output: "48" Input: s1 = "00", s2 = "000"Output: "0" Input: s1 = "10000000", s2 = "89990000"Output: 99990000 One by One Addin
    7 min read
  • Summation of Alphanumeric Strings
    Just like our number system where we have 10 digits starting from 0 to 9, Geek has created a custom numerical system where he has 36 digits which are 0 to 9 then A to Z where '0' is the smallest, and 'Z' is the largest number, which follows their respective order (Similar to Hexadecimal number syste
    11 min read
  • String from prefix and suffix of given two strings
    Given two strings a and b, form a new string of length l, from these strings by combining the prefix of string a and suffix of string b. Examples : Input : string a = remuneration string b = acquiesce length of pre/suffix(l) = 5 Output :remuniesce Input : adulation obstreperous 6 Output :adulatperou
    4 min read
  • Perform range sum queries on string as per given condition
    Given a string S with lowercase alphabets only and Q queries where each query contains a pair {L, R}. For each query {L, R}, there exists a substring S[L, R], the task is to find the value of the product of the frequency of each character in substring with their position in alphabetical order. Note:
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences