📌  相关文章
📜  给定数字字符串的所有前缀的总和

📅  最后修改于: 2022-05-13 01:56:10.044000             🧑  作者: Mango

给定数字字符串的所有前缀的总和

给定字符串strN个字符表示一个整数,任务是计算给定字符串的所有可能前缀的总和。

例子:

方法:给定的问题是一个基于实现的问题,可以通过迭代字符串的所有前缀并将它们的总和保存在一个字符串中来解决。表示为字符串的两个整数之和可以使用这里讨论的方法来完成。

下面是上述方法的实现:

C++
// C++ program of the above approach
#include 
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



输出
1360

时间复杂度: O(N 2 )
辅助空间: O(N)