Skip to content
Related Articles
Open in App
Not now

Related Articles

Reversing an Equation

Improve Article
Save Article
Like Article
  • Difficulty Level : Basic
  • Last Updated : 13 Mar, 2023
Improve Article
Save Article
Like Article

Given a mathematical equation using numbers/variables and +, -, *, /. Print the equation in reverse.

Examples:  

Input : 20 - 3 + 5 * 2
Output : 2 * 5 + 3 - 20

Input : 25 + 3 - 2 * 11
Output : 11 * 2 - 3 + 25

Input : a + b * c - d / e
Output : e / d - c * b + a
Recommended Practice

Approach : The approach to this problem is simple. We iterate the string from left to right and as soon we strike a symbol we insert the number and the symbol in the beginning of the resultant string.

Implementation:

C++




// C++ program to reverse an equation
#include <bits/stdc++.h>
using namespace std;
 
// Function to reverse order of words
string reverseEquation(string s)
{
    // Resultant string
    string result;
    int j = 0;
    for (int i = 0; i < s.length(); i++) {
         
        // A space marks the end of the word
        if (s[i] == '+' || s[i] == '-' ||
            s[i] == '/' || s[i] == '*') {
             
            // insert the word at the beginning
            // of the result string
            result.insert(result.begin(),
                s.begin() + j, s.begin() + i);
            j = i + 1;
             
            // insert the symbol
            result.insert(result.begin(), s[i]);
        }
    }
     
    // insert the last word in the string
    // to the result string
    result.insert(result.begin(), s.begin() + j,
                                     s.end());
    return result;
}
 
// driver code
int main()
{
    string s = "a+b*c-d/e";
    cout << reverseEquation(s) << endl;
    return 0;
}


Java




// Java program to reverse an equation
import java.util.*;
 
class GFG{
     
// Function to reverse order of words
public static String reverseEquation(String s)
{
     
    // Resultant string
    String result = "", str = "";
    int j = 0;
     
    for(int i = 0; i < s.length(); i++)
    {
         
        // A space marks the end of the word
        if (s.charAt(i) == '+' ||
            s.charAt(i) == '-' ||
            s.charAt(i) == '/' ||
            s.charAt(i) == '*')
        {
             
            // Insert the word at the beginning
            // of the result string
            result = s.charAt(i) + str + result;
            str = "";
        }
        else
        {
            str += s.charAt(i);
        }
    }
    result = str + result;
    return result;
}
 
// Driver code
public static void main(String args[])
{
    String s = "a+b*c-d/e";
     
    System.out.println(reverseEquation(s));
}
}
 
// This code is contributed by bolliranadheer


C#




// C# program to reverse an equation
using System;
using System.Text;
 
public class GFG{
 
  // Function to reverse order of words
  public static string reverseEquation(string s)
  {
     
    // Resultant string
    string result = "", str = "";
 
    for(int i = 0; i < s.Length; i++)
    {
 
      // A space marks the end of the word
      if (s[i] == '+' || s[i] == '-' || s[i] == '/' || s[i] == '*')
      {
 
        // Insert the word at the beginning
        // of the result string
        result = s[i] + str + result;
        str = "";
      }
      else
      {
        str += s[i];
      }
    }
    result = str + result;
    return result;
  }
 
  // Driver Code
  static public void Main (){
 
    string s = "a+b*c-d/e";
 
    Console.Write(reverseEquation(s));
  }
}
 
// This code is contributed by shruti456rawal


Python3




# Python3 Program to reverse an equation
# Function to reverse order of words
def reverseEquation(s):
     
    # Reverse String
    result=""
    for i in range(len(s)):
         
        # A space marks the end of the word
        if(s[i]=='+' or s[i]=='-' or s[i]=='/' or s[i]=='*'):
             
            # insert the word at the beginning
            # of the result String
            result = s[i] + result
         
        # insert the symbol
        else:
            result = s[i] + result
    return result
 
# Driver Code
s = "a+b*c-d/e"
print(reverseEquation(s))
 
# This code is contributed by simranjenny84


Javascript




// JavaScript program to reverse an equation
 
// Function to reverse order of words
function reverseEquation(s) {
    // Resultant string
    let result = "", str = "";
 
    for (let i = 0; i < s.length; i++) {
        // A space marks the end of the word
        if (s[i] === "+" || s[i] === "-" || s[i] === "/" || s[i] === "*") {
            // Insert the word at the beginning
            // of the result string
            result = s[i] + str + result;
            str = "";
        }
        else {
              str += s[i];
        }
    }
    result = str + result;
    return result;
}
 
let s = "a+b*c-d/e";
console.log(reverseEquation(s));
 
// This code is contributed by lokeshmvs21.


Output

e/d-c*b+a

Time Complexity: O(N)
Auxiliary Space: O(N) because it is using extra space for string result

 By using Standard library

Approach-  By using stl library you can directly reverse a string and it is easy to implement. For more clarification, you can see the below implementation-

C++




// C++ program to reverse an equation
#include <bits/stdc++.h>
using namespace std;
 
// driver code
int main()
{
    string s = "a+b*c-d/e";
      reverse(s.begin(),s.end());
    cout << s << endl;
    return 0;
}
 
//code by ksam24000


Java




// java implementation
 
import java.util.*;
 
public class Main {
    public static void main(String[] args)
    {
        String s = "a+b*c-d/e";
        StringBuilder sb = new StringBuilder(s);
        sb.reverse();
        System.out.println(sb.toString());
    }
}
// code by ksam24000


Python3




#python program to reverse an equation
def reverse_equation(s):
  return s[::-1]
 
s = "a+b*c-d/e"
print(reverse_equation(s))
 
# code by ksam24000


C#




// c# code implementation
 
using System;
 
public class GFG {
 
    static public void Main()
    {
        string s = "a+b*c-d/e";
        char[] arr = s.ToCharArray();
        Array.Reverse(arr);
        Console.WriteLine(new string(arr));
        // Code
    }
}
 
// code by ksam24000


Javascript




function reverse_equation(s) {
  return s.split('').reverse().join('');
}
 
let s = "a+b*c-d/e";
console.log(reverse_equation(s));
 
// THIS CODE IS CONTRIBUTED BY KIRTI AGARWAL


Output

e/d-c*b+a

Time-complexity :- O(n)
Auxiliary complexity :- O(1)

This article is contributed by Raghav Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. 


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!