Elimina los ceros finales de la suma de dos números (Usando Stack)

Dados dos números A y B , la tarea es eliminar los ceros finales presentes en la suma de los dos números dados usando una pila .

Ejemplos:

Entrada: A = 124, B = 186
Salida: 31
Explicación: La suma de A y B es 310. Al eliminar los ceros finales, la suma se modifica a 31.

Entrada: A=130246, B= 450164
Salida: 58041

Enfoque: el problema dado se puede resolver utilizando las estructuras de datos de string y pila . Siga los pasos a continuación para resolver el problema:

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

C++14

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to remove trailing
// zeros from the sum of two numbers
string removeTrailing(int A, int B)
{
    // Stores the sum of A and B
    int N = A + B;
 
    // Stores the digits
    stack<int> s;
 
    // Stores the equivalent
    // string of integer N
    string strsum = to_string(N);
 
    // Traverse the string
    for (int i = 0; i < strsum.length(); i++) {
 
        // Push the digit at i
        // in the stack
        s.push(strsum[i]);
    }
 
    // While top element is '0'
    while (s.top() == '0')
 
        // Pop the top element
        s.pop();
 
    // Stores the resultant number
    // without trailing 0's
    string res = "";
 
    // While s is not empty
    while (!s.empty()) {
 
        // Append top element of S in res
        res = res + char(s.top());
 
        // Pop the top element of S
        s.pop();
    }
 
    // Reverse the string res
    reverse(res.begin(), res.end());
 
    return res;
}
 
// Driver Code
int main()
{
    // Input
    int A = 130246, B = 450164;
 
    // Function Call
    cout << removeTrailing(A, B);
    return 0;
}

Java

// Java program for the above approach
import java.io.*;
import java.util.*;
 
class GFG{
 
// Function to remove trailing
// zeros from the sum of two numbers
static String removeTrailing(int A, int B)
{
     
    // Stores the sum of A and B
    int N = A + B;
 
    // Stores the digits
    Stack<Character> s = new Stack<Character>();
 
    // Stores the equivalent
    // string of integer N
    String strsum = Integer.toString(N);
 
    // Traverse the string
    for(int i = 0; i < strsum.length(); i++)
    {
         
        // Push the digit at i
        // in the stack
        s.push(strsum.charAt(i));
    }
 
    // While top element is '0'
    while (s.peek() == '0')
    {
         
        // Pop the top element
        s.pop();
    }
 
    // Stores the resultant number
    // without trailing 0's
    String res = "";
 
    // While s is not empty
    while (s.empty() == false)
    {
         
        // Append top element of S in res
        res = res + (char)s.peek();
 
        // Pop the top element of S
        s.pop();
    }
 
    StringBuilder str = new StringBuilder();
    str.append(res);
 
    // Reverse the string res
    str.reverse();
 
    return str.toString();
}
 
// Driver Code
public static void main (String[] args)
{
     
    // Input
    int A = 130246, B = 450164;
 
    // Function Call
    System.out.println(removeTrailing(A, B));
}
}
 
// This code is contributed by Dharanendra.L.V.

Python3

# Python 3 program for the above approach
 
# Function to remove trailing
# zeros from the sum of two numbers
def removeTrailing(A,  B):
 
    # Stores the sum of A and B
    N = A + B
 
    # Stores the digits
    s = []
 
    # Stores the equivalent
    # string of integer N
    strsum = str(N)
 
    # Traverse the string
    for i in range(len(strsum)):
 
        # Push the digit at i
        # in the stack
        s.append(strsum[i])
 
    # While top element is '0'
    while (s[-1] == '0'):
 
        # Pop the top element
        s.pop()
 
    # Stores the resultant number
    # without trailing 0's
    res = ""
 
    # While s is not empty
    while (len(s) != 0):
 
        # Append top element of S in res
        res = res + (s[-1])
 
        # Pop the top element of S
        s.pop()
 
    # Reverse the string res
    res = list(res)
    res.reverse()
    res = ''.join(res)
 
    return res
 
 
# Driver Code
if __name__ == "__main__":
 
    # Input
    A = 130246
    B = 450164
 
    # Function Call
    print(removeTrailing(A, B))
 
    # This code is contributed by ukasp.

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
     
// Function to remove trailing
// zeros from the sum of two numbers
static string removeTrailing(int A, int B)
{
     
    // Stores the sum of A and B
    int N = A + B;
  
    // Stores the digits
    Stack<char> s = new Stack<char>();
  
    // Stores the equivalent
    // string of integer N
    string strsum = N.ToString();
  
    // Traverse the string
    for(int i = 0; i < strsum.Length; i++)
    {
          
        // Push the digit at i
        // in the stack
        s.Push(strsum[i]);
    }
  
    // While top element is '0'
    while (s.Peek() == '0')
    {
          
        // Pop the top element
        s.Pop();
    }
  
    // Stores the resultant number
    // without trailing 0's
    string res = "";
  
    // While s is not empty
    while (s.Count != 0)
    {
          
        // Append top element of S in res
        res = res + (char)s.Peek();
  
        // Pop the top element of S
        s.Pop();
    }
     
    char[] str = res.ToCharArray();
    Array.Reverse(str);
     
    // Reverse the string res
    return new string( str);
}
  
// Driver Code
static public void Main()
{
     
    // Input
    int A = 130246, B = 450164;
     
    // Function Call
    Console.WriteLine(removeTrailing(A, B));
}
}
 
// This code is contributed by avanitrachhadiya2155

Javascript

<script>
 
        // Javascript program for the above approach
 
        // Function to remove trailing
        // zeros from the sum of two numbers
        function removeTrailing(A, B) {
 
            // Stores the sum of A and B
            let N = A + B;
 
            // Stores the digits
            let s = new Array();
 
            // Stores the equivalent
            // string of integer N
            let strsum = N.toString();
 
            // Traverse the string
            for (let i = 0; i < strsum.length; i++) {
 
                // Push the digit at i
                // in the stack
                s.push(strsum.charAt(i));
            }
 
            // While top element is '0'
            while (s[s.length-1] === '0') {
 
                // Pop the top element
                s.pop();
            }
        
            // Stores the resultant number
            // without trailing 0's
            let res = "";
 
            // While s is not empty
            while (s.length != 0) {
 
                // Append top element of S in res
                res = res.concat(s[s.length-1]);
 
                // Pop the top element of S
                s.pop();
            }
 
            let str = "";
            str = str.concat(res)
 
            // Reverse the string res
            str = str.split("").reverse().join("");
 
            return str.toString();
        }
 
        // Driver Code
 
        // Input
        let A = 130246, B = 450164;
 
        // Function Call
        document.write(removeTrailing(A, B));
 
        // This code is contributed by Hritik
         
    </script>
Producción: 

58041

 

Complejidad de Tiempo: O(len(A + B))
Espacio Auxiliar: O(len(A + B))

Publicación traducida automáticamente

Artículo escrito por vikkycirus 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 *