Saturday, 16 Oct 2021

# Remove trailing zeros from the sum of two numbers ( Using Stack )

Remove trailing zeros from the sum of two numbers ( Using Stack )Given two numbers A and B, the task is to remove the trailing zeros present in the sum of the two given numbers using a stack.Examples:Input: A = 124, B = 186Output: 31Explanation: Sum of A and B is 310. Removing the trailing zeros modifies the sum to 31.Input: A=130246, B= 450164Output : 58041Approach: The given problem can be solved using the string and stack data structures. Follow the steps below to solve the problem:Calculate A + B and store it in a variable, say N.Initialize a stack < char > , say S, to store the digits of N.Convert the integer N to string and then push the characters into the stack S.Iterate while S is not empty(), If the top element of the stack is ‘0’, then pop it out of the stack. Otherwise, break.Initialize a string, say res, to store the resultant string.Iterate while S is not empty(), and push all the characters in res and, then pop the top element.Reverse the string res and print the res as the answer.Below is the implementation of the above approach:C++14#include using namespace std;  string removeTailing(int A, int B){        int N = A + B;          stack s;              string strsum = to_string(N);          for (int i = 0; i < strsum.length(); i++) {                          s.push(strsum[i]);    }          while (s.top() == '0')                  s.pop();              string res = "";          while (!s.empty()) {                  res = res + char(s.top());                  s.pop();    }          reverse(res.begin(), res.end());      return res;}  int main(){        int A = 130246, B = 450164;          cout