📜  大数数组的总和

📅  最后修改于: 2021-09-04 11:25:25             🧑  作者: Mango

给定一个整数K和一个由N 个大数组成的字符串数组arr[] ,任务是找到数组中所有大数的和。

例子:

方法:思路是将所有数字对应位置的数字相加。创建一个大小为K + 1的数组result[]来存储结果。从末尾遍历所有字符串,并继续将所有数字的相同位置的数字相加,并将其插入到result[] 中的相应索引中。以下是步骤:

  1. 初始化一个数组result[]来存储数字的总和。
  2. 迭代从索引K 到 0的字符串,并对每个索引执行以下操作:
    • 遍历所有数组元素并计算当前索引处所有数字的总和,例如idx ,并存储在变量中,例如sum
    • 将数字放在result[idx] 中上述总和的某个位置。
    • sum / 10的值存储为下一个索引的进位。
  3. 在对所有数组的整个长度重复上述步骤后,将存储在result[] 中的所有数字反转以获得给定N 个数字的结果总和。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to print the result of the
// summation of numbers having K-digit
void printResult(vector result)
{
    // Reverse the array to
    // obtain the result
    reverse(result.begin(), result.end());
 
    int i = 0;
 
    while (i < result.size()) {
 
        // Print every digit
        // of the answer
        cout << result[i];
        i++;
    }
}
 
// Function to calculate the total sum
void sumOfLargeNumbers(string v[], int k, int N)
{
    // Stores the array of large
    // numbers in integer format
    vector > x(1000);
 
    for (int i = 0; i < k; i++) {
 
        for (int j = 0; j < N; j++) {
 
            // Convert each element
            // from character to integer
            x[i].push_back(v[i][j] - '0');
        }
    }
 
    // Stores the carry
    int carry = 0;
 
    // Stores the result
    // of summation
    vector result;
 
    for (int i = N - 1; i >= 0; i--) {
 
        // Initialize the sum
        int sum = 0;
 
        for (int j = 0; j < k; j++)
 
            // Calculate sum
            sum += x[j][i];
 
        // Update the sum by adding
        // existing carry
        sum += carry;
        int temp = sum;
 
        // Store the number of digits
        int count = 0;
        while (temp > 9) {
            temp = temp % 10;
 
            // Increase count of digits
            count++;
        }
 
        long long int l = pow(10, count);
        if (l != 1)
 
            // If the number exceeds 9,
            // Store the unit digit in carry
            carry = (double)sum / l;
 
        // Store the rest of the sum
        sum = sum % 10;
 
        // Append digit by digit
        // into result array
        result.push_back(sum);
    }
    while (carry != 0) {
        int a = carry % 10;
 
        // Append result until
        // carry is 0
        result.push_back(a);
        carry = carry / 10;
    }
 
    // Print the result
    printResult(result);
}
 
// Driver Code
int main()
{
    int K = 10;
    int N = 5;
 
    // Given N array of large numbers
    string arr[]
        = { "1111111111", "1111111111",
            "1111111111", "1111111111",
            "1111111111" };
 
    sumOfLargeNumbers(arr, N, K);
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
import java.lang.*;
 
class GFG{
 
// Function to print the result of the
// summation of numbers having K-digit
static void printResult(ArrayList result)
{
     
    // Reverse the array to
    // obtain the result
    Collections.reverse(result);
 
    int i = 0;
 
    while (i < result.size())
    {
         
        // Print every digit
        // of the answer
        System.out.print(result.get(i));
        i++;
    }
}
 
// Function to calculate the total sum
static void sumOfLargeNumbers(String v[],
                              int k, int N)
{
     
    // Stores the array of large
    // numbers in integer format
    ArrayList<
    ArrayList> x = new ArrayList<>(1000);
 
    for(int i = 0; i < k; i++)
        x.add(new ArrayList());
 
    for(int i = 0; i < k; i++)
    {
        for(int j = 0; j < N; j++)
        {
 
            // Convert each element
            // from character to integer
            x.get(i).add(v[i].charAt(j) - '0');
        }
    }
 
    // Stores the carry
    int carry = 0;
 
    // Stores the result
    // of summation
    ArrayList result = new ArrayList<>();
 
    for(int i = N - 1; i >= 0; i--)
    {
         
        // Initialize the sum
        int sum = 0;
 
        for(int j = 0; j < k; j++)
 
            // Calculate sum
            sum += x.get(j).get(i);
 
        // Update the sum by adding
        // existing carry
        sum += carry;
        int temp = sum;
 
        // Store the number of digits
        int count = 0;
        while (temp > 9)
        {
            temp = temp % 10;
 
            // Increase count of digits
            count++;
        }
 
        long l = (long)Math.pow(10, count);
        if (l != 1)
         
            // If the number exceeds 9,
            // Store the unit digit in carry
            carry = (int)(sum / l);
 
        // Store the rest of the sum
        sum = sum % 10;
 
        // Append digit by digit
        // into result array
        result.add(sum);
    }
    while (carry != 0)
    {
        int a = carry % 10;
 
        // Append result until
        // carry is 0
        result.add(a);
        carry = carry / 10;
    }
 
    // Print the result
    printResult(result);
}
 
// Driver Code
public static void main (String[] args)
{
    int K = 10;
    int N = 5;
     
    // Given N array of large numbers
    String arr[]  = { "1111111111", "1111111111",
                      "1111111111", "1111111111",
                      "1111111111" };
     
    sumOfLargeNumbers(arr, N, K);
}
}
 
// This code is contributed by offbeat


Python3
# Python3 program for the above approach
 
# Function to prthe result of the
# summation of numbers having K-digit
def printResult(result):
 
    # Reverse the array to
    # obtain the result
    result = result[::-1]
 
    i = 0
    while (i < len(result)):
 
        # Print every digit
        # of the answer
        print(result[i], end = "")
        i += 1
 
# Function to calculate the total sum
def sumOfLargeNumbers(v, k, N):
 
    # Stores the array of large
    # numbers in integer format
    x = [[] for i in range(1000)]
 
    for i in range(k):
        for j in range(N):
 
            # Convert each element
            # from character to integer
            x[i].append(ord(v[i][j]) - ord('0'))
 
    # Stores the carry
    carry = 0
 
    # Stores the result
    # of summation
    result = []
 
    for i in range(N - 1, -1, -1):
 
        # Initialize the sum
        sum = 0
 
        for j in range(k):
 
            # Calculate sum
            sum += x[j][i]
 
        # Update the sum by adding
        # existing carry
        sum += carry
        temp = sum
 
        # Store the number of digits
        count = 0
        while (temp > 9):
            temp = temp % 10
 
            # Increase count of digits
            count += 1
 
        l = pow(10, count)
        if (l != 1):
 
            # If the number exceeds 9,
            # Store the unit digit in carry
            carry = sum / l
 
        # Store the rest of the sum
        sum = sum % 10
 
        # Append digit by digit
        # into result array
        result.append(sum)
 
    while (carry != 0):
        a = carry % 10
 
        # Append result until
        # carry is 0
        result.append(a)
        carry = carry // 10
 
    # Print the result
    printResult(result)
 
# Driver Code
if __name__ == '__main__':
     
    K = 10
    N = 5
 
    # Given N array of large numbers
    arr= [ "1111111111", "1111111111",
           "1111111111", "1111111111",
           "1111111111" ]
 
    sumOfLargeNumbers(arr, N, K)
 
# This code is contributed by mohit kumar 29


C#
// C# program for
// the above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Function to print the result of the
// summation of numbers having K-digit
static void printResult(List result)
{
  // Reverse the array to
  // obtain the result
  result.Reverse();
 
  int i = 0;
 
  while (i < result.Count)
  {
 
    // Print every digit
    // of the answer
    Console.Write(result[i]);
    i++;
  }
}
 
// Function to calculate the total sum
static void sumOfLargeNumbers(String []v,
                              int k, int N)
{  
  // Stores the array of large
  // numbers in integer format
  List> x =
            new List>(1000);
 
  for(int i = 0; i < k; i++)
    x.Add(new List());
 
  for(int i = 0; i < k; i++)
  {
    for(int j = 0; j < N; j++)
    {
      // Convert each element
      // from character to integer
      x[i].Add(v[i][j] - '0');
    }
  }
 
  // Stores the carry
  int carry = 0;
 
  // Stores the result
  // of summation
  List result = new List();
 
  for(int i = N - 1; i >= 0; i--)
  {
    // Initialize the sum
    int sum = 0;
 
    for(int j = 0; j < k; j++)
 
      // Calculate sum
      sum += x[j][i];
 
    // Update the sum by adding
    // existing carry
    sum += carry;
    int temp = sum;
 
    // Store the number of digits
    int count = 0;
    while (temp > 9)
    {
      temp = temp % 10;
 
      // Increase count of digits
      count++;
    }
 
    long l = (long)Math.Pow(10, count);
    if (l != 1)
 
      // If the number exceeds 9,
      // Store the unit digit in carry
      carry = (int)(sum / l);
 
    // Store the rest of the sum
    sum = sum % 10;
 
    // Append digit by digit
    // into result array
    result.Add(sum);
  }
   
  while (carry != 0)
  {
    int a = carry % 10;
 
    // Append result until
    // carry is 0
    result.Add(a);
     
    carry = carry / 10;
  }
 
  // Print the result
  printResult(result);
}
 
// Driver Code
public static void Main(String[] args)
{
  int K = 10;
  int N = 5;
 
  // Given N array of large numbers
  String []arr  = {"1111111111",
                   "1111111111",
                   "1111111111",
                   "1111111111",
                   "1111111111"};
 
  sumOfLargeNumbers(arr, N, K);
}
}
 
// This code is contributed by Rajput-Ji


输出:
5555555555


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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live