Suma de dos números donde un número se representa como una array de dígitos

Dada una array arr[] de dígitos y un entero K , la tarea es encontrar num(arr) + K donde num(arr) es el número formado al concatenar todos los dígitos de la array.

Ejemplos: 

Entrada: arr[] = {2, 7, 4}, K = 181 
Salida: 455 
274 + 181 = 455

Entrada: arr[] = {6}, K = 815 
Salida: 821 
6 + 815 = 821 

Enfoque: comience a recorrer la array de dígitos desde el final y comience a agregar los dígitos de K uno por uno al dígito actual, si se genera algún acarreo, agréguelo a la siguiente adición de dígitos. Después de que se hayan agregado todos los dígitos de K, comience a recorrer la array de dígitos desde la izquierda y comience a imprimir los elementos que, al concatenar, darán el número resultante.

A continuación se muestra la implementación del enfoque anterior: 

C++

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the vector containing the answer
vector<int> addToArrayForm(vector<int>& A, int K)
{
 
    // Vector v is to store each digits sum
    // and vector ans is to store the answer
    vector<int> v, ans;
 
    // No carry in the beginning
    int rem = 0;
 
    int i = 0;
 
    // Start loop from the end
    // and take element one by one
    for (i = A.size() - 1; i >= 0; i--) {
 
        // Array index and last digit of number
        int my = A[i] + K % 10 + rem;
        if (my > 9) {
 
            // Maintain carry of summation
            rem = 1;
 
            // Push the digit value into the array
            v.push_back(my % 10);
        }
        else {
            v.push_back(my);
            rem = 0;
        }
        K = K / 10;
    }
 
    // K value is greater then 0
    while (K > 0) {
 
        // Push digits of K one by one in the array
        int my = K % 10 + rem;
        v.push_back(my % 10);
 
        // Also maintain carry with summation
        if (my / 10 > 0)
            rem = 1;
        else
            rem = 0;
        K = K / 10;
    }
 
    if (rem > 0)
        v.push_back(rem);
 
    // Reverse the elements of vector v
    // and store it in vector ans
    for (int i = v.size() - 1; i >= 0; i--)
        ans.push_back(v[i]);
 
    return ans;
}
 
// Driver code
int main()
{
    vector<int> A{ 2, 7, 4 };
    int K = 181;
    vector<int> ans = addToArrayForm(A, K);
 
    // Print the answer
    for (int i = 0; i < ans.size(); i++)
        cout << ans[i];
 
    return 0;
}

Java

// Java implementation of the approach
import java.util.*;
 
class GFG
{
    // Function to return the vector containing the answer
    static ArrayList<Integer> addToArrayForm(ArrayList<Integer> A, int K)
    {
     
        // ArrayList v is to store each digits sum
        // and ArrayList ans is to store the answer
        ArrayList<Integer> v = new ArrayList<Integer>();
        ArrayList<Integer> ans = new ArrayList<Integer>();
         
        // No carry in the beginning
        int rem = 0;
     
        int i = 0;
     
        // Start loop from the end
        // and take element one by one
        for (i = A.size() - 1; i >= 0; i--)
        {
     
            // Array index and last digit of number
            int my = A.get(i) + K % 10 + rem;
            if (my > 9)
            {
     
                // Maintain carry of summation
                rem = 1;
     
                // Push the digit value into the array
                v.add(my % 10);
            }
            else
            {
                v.add(my);
                rem = 0;
            }
            K = K / 10;
        }
     
        // K value is greater then 0
        while (K > 0)
        {
     
            // Push digits of K one by one in the array
            int my = K % 10 + rem;
            v.add(my % 10);
     
            // Also maintain carry with summation
            if (my / 10 > 0)
                rem = 1;
            else
                rem = 0;
            K = K / 10;
        }
     
        if (rem > 0)
            v.add(rem);
     
        // Reverse the elements of vector v
        // and store it in vector ans
        for (int j = v.size() - 1; j >= 0; j--)
            ans.add(v.get(j));
     
        return ans;
    }
     
    // Driver code
    public static void main (String[] args)
    {
        ArrayList<Integer> A = new ArrayList<Integer>();
        A.add(2);
        A.add(7);
        A.add(4);
         
         
        int K = 181;
        ArrayList<Integer> ans = addToArrayForm(A, K);
     
        // Print the answer
        for (int i = 0; i < ans.size(); i++)
            System.out.print(ans.get(i));
     
    }
}
 
// This code is contributed by ihritik

Python3

# Python3 implementation of the approach
 
# Function to return the vector
# containing the answer
def addToArrayForm(A, K):
 
    # Vector v is to store each digits sum
    # and vector ans is to store the answer
    v, ans = [], []
 
    # No carry in the beginning
    rem, i = 0, 0
 
    # Start loop from the end
    # and take element one by one
    for i in range(len(A) - 1, -1, -1):
 
        # Array index and last digit of number
        my = A[i] + (K % 10) + rem
        if my > 9:
 
            # Maintain carry of summation
            rem = 1
 
            # Push the digit value into the array
            v.append(my % 10)
         
        else:
            v.append(my)
            rem = 0
         
        K = K // 10
     
    # K value is greater then 0
    while K > 0:
 
        # Push digits of K one by one in the array
        my = (K % 10) + rem
        v.append(my % 10)
 
        # Also maintain carry with summation
        if my // 10 > 0:
            rem = 1
        else:
            rem = 0
         
        K = K // 10
     
    if rem > 0:
        v.append(rem)
 
    # Reverse the elements of vector v
    # and store it in vector ans
    for i in range(len(v) - 1, -1, -1):
        ans.append(v[i])
 
    return ans
 
# Driver code
if __name__ == "__main__":
 
    A = [2, 7, 4]
    K = 181
    ans = addToArrayForm(A, K)
 
    # Print the answer
    for i in range(0, len(ans)):
        print(ans[i], end = "")
 
# This code is contributed by Rituraj Jain

C#

// C# implementation of the approach
using System;
using System.Collections;
 
class GFG
{
    // Function to return the vector containing the answer
    static ArrayList addToArrayForm(ArrayList A, int K)
    {
     
        // ArrayList v is to store each digits sum
        // and ArrayList ans is to store the answer
        ArrayList v = new ArrayList();
        ArrayList ans = new ArrayList();
         
        // No carry in the beginning
        int rem = 0;
     
        int i = 0;
     
        // Start loop from the end
        // and take element one by one
        for (i = A.Count - 1; i >= 0; i--)
        {
     
            // Array index and last digit of number
            int my = (int)A[i] + K % 10 + rem;
            if (my > 9)
            {
     
                // Maintain carry of summation
                rem = 1;
     
                // Push the digit value into the array
                v.Add(my % 10);
            }
            else
            {
                v.Add(my);
                rem = 0;
            }
            K = K / 10;
        }
     
        // K value is greater then 0
        while (K > 0)
        {
     
            // Push digits of K one by one in the array
            int my = K % 10 + rem;
            v.Add(my % 10);
     
            // Also maintain carry with summation
            if (my / 10 > 0)
                rem = 1;
            else
                rem = 0;
            K = K / 10;
        }
     
        if (rem > 0)
            v.Add(rem);
     
        // Reverse the elements of vector v
        // and store it in vector ans
        for (int j = v.Count - 1; j >= 0; j--)
            ans.Add((int)v[j]);
     
        return ans;
    }
     
    // Driver code
    static void Main()
    {
        ArrayList A = new ArrayList();
        A.Add(2);
        A.Add(7);
        A.Add(4);
         
        int K = 181;
        ArrayList ans = addToArrayForm(A, K);
     
        // Print the answer
        for (int i = 0; i < ans.Count; i++)
            Console.Write((int)ans[i]);
    }
}
 
// This code is contributed by mits

PHP

<?php
// Php implementation of the approach
 
// Function to return the vector containing the answer
function addToArrayForm($A, $K)
{
 
    // Vector v is to store each digits sum
    // and vector ans is to store the answer
    $v = array();
    $ans = array();
 
    // No carry in the beginning
    $rem = 0;
 
    $i = 0;
 
    // Start loop from the end
    // and take element one by one
    for ($i = count($A) - 1; $i >= 0; $i--)
    {
 
        // Array index and last digit of number
        $my = $A[$i] + $K % 10 + $rem;
        if ($my > 9)
        {
 
            // Maintain carry of summation
            $rem = 1;
 
            // Push the digit value into the array
            array_push($v,$my % 10);
        }
        else
        {
            array_push($v,$my);
            $rem = 0;
        }
        $K = floor($K / 10);
    }
 
    // K value is greater then 0
    while ($K > 0)
    {
 
        // Push digits of K one by one in the array
        $my = $K % 10 + $rem;
         
        array_push($v,$my % 10);
 
        // Also maintain carry with summation
        if ($my / 10 > 0)
            $rem = 1;
        else
            $rem = 0;
             
        $K = floor($K / 10);
    }
 
    if ($rem > 0)
        array_push($v,$rem);
 
    // Reverse the elements of vector v
    // and store it in vector ans
    for ($i = count($v) - 1; $i >= 0; $i--)
        array_push($ans,$v[$i]);
 
    return $ans;
}
 
// Driver code
$A = array( 2, 7, 4 );
$K = 181;
$ans = addToArrayForm($A, $K);
 
// Print the answer
for ($i = 0; $i < count($ans); $i++)
    echo $ans[$i];
     
// This code is contributed by Ryuga
?>

Javascript

<script>
 
// Javascript implementation of the approach
 
// Function to return the vector
// containing the answer
function addToArrayForm(A, K)
{
     
    // ArrayList v is to store each digits sum
    // and ArrayList ans is to store the answer
    let v = [];
    let ans = [];
       
    // No carry in the beginning
    let rem = 0;
   
    let i = 0;
   
    // Start loop from the end
    // and take element one by one
    for(i = A.length - 1; i >= 0; i--)
    {
         
        // Array index and last digit of number
        let my = A[i] + K % 10 + rem;
        if (my > 9)
        {
             
            // Maintain carry of summation
            rem = 1;
   
            // Push the digit value into the array
            v.push(my % 10);
        }
        else
        {
            v.push(my);
            rem = 0;
        }
        K = parseInt(K / 10, 10);
    }
   
    // K value is greater then 0
    while (K > 0)
    {
   
        // Push digits of K one by one in the array
        let my = K % 10 + rem;
        v.push(my % 10);
   
        // Also maintain carry with summation
        if (parseInt(my / 10, 10) > 0)
            rem = 1;
        else
            rem = 0;
             
        K = parseInt(K / 10, 10);
    }
   
    if (rem > 0)
        v.push(rem);
   
    // Reverse the elements of vector v
    // and store it in vector ans
    for(let j = v.length - 1; j >= 0; j--)
        ans.push(v[j]);
   
    return ans;
}
 
// Driver code
let A = [];
A.push(2);
A.push(7);
A.push(4);
 
let K = 181;
let ans = addToArrayForm(A, K);
 
// Print the answer
for(let i = 0; i < ans.length; i++)
    document.write(ans[i]);
     
// This code is contributed by divyeshrabadiya07
 
</script>
Producción: 

455

 

Complejidad temporal: O(n + log K)

Espacio Auxiliar: O(n + log K)

Publicación traducida automáticamente

Artículo escrito por Sumit bangar y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *