Reversing an Equation
Last Updated :
28 Jun, 2023
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
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++
#include <bits/stdc++.h>
using namespace std;
string reverseEquation(string s)
{
string result;
int j = 0;
for ( int i = 0; i < s.length(); i++) {
if (s[i] == '+' || s[i] == '-' ||
s[i] == '/' || s[i] == '*' ) {
result.insert(result.begin(),
s.begin() + j, s.begin() + i);
j = i + 1;
result.insert(result.begin(), s[i]);
}
}
result.insert(result.begin(), s.begin() + j,
s.end());
return result;
}
int main()
{
string s = "a+b*c-d/e" ;
cout << reverseEquation(s) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG{
public static String reverseEquation(String s)
{
String result = "" , str = "" ;
int j = 0 ;
for ( int i = 0 ; i < s.length(); i++)
{
if (s.charAt(i) == '+' ||
s.charAt(i) == '-' ||
s.charAt(i) == '/' ||
s.charAt(i) == '*' )
{
result = s.charAt(i) + str + result;
str = "" ;
}
else
{
str += s.charAt(i);
}
}
result = str + result;
return result;
}
public static void main(String args[])
{
String s = "a+b*c-d/e" ;
System.out.println(reverseEquation(s));
}
}
|
Python3
def reverseEquation(s):
result = ""
for i in range ( len (s)):
if (s[i] = = '+' or s[i] = = '-' or s[i] = = '/' or s[i] = = '*' ):
result = s[i] + result
else :
result = s[i] + result
return result
s = "a+b*c-d/e"
print (reverseEquation(s))
|
C#
using System;
using System.Text;
public class GFG{
public static string reverseEquation( string s)
{
string result = "" , str = "" ;
for ( int i = 0; i < s.Length; i++)
{
if (s[i] == '+' || s[i] == '-' || s[i] == '/' || s[i] == '*' )
{
result = s[i] + str + result;
str = "" ;
}
else
{
str += s[i];
}
}
result = str + result;
return result;
}
static public void Main (){
string s = "a+b*c-d/e" ;
Console.Write(reverseEquation(s));
}
}
|
Javascript
function reverseEquation(s) {
let result = "" , str = "" ;
for (let i = 0; i < s.length; i++) {
if (s[i] === "+" || s[i] === "-" || s[i] === "/" || s[i] === "*" ) {
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));
|
Time Complexity: O(N)
Auxiliary Space: O(N) because it is using extra space for string result
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...