# Reversing an Equation

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.

`// CPP 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 begining ` ` ` `// 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; ` `} ` |

*chevron_right*

*filter_none*

Output:

e/d-c*b+a

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

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

## Recommended Posts:

- Find the missing value from the given equation a + b = c
- Validation of Equation Given as String
- Check if string can be made lexicographically smaller by reversing any substring
- Total number of odd length palindrome sub-sequence around each centre
- Count of substrings which contains a given character K times
- Count of sub-sequences which satisfy the given condition
- Largest sub-string where all the characters appear at least K times
- Queries to find the first non-repeating character in the sub-string of a string
- Minimum rotations required to get the same String | Set-2
- Find if it is possible to make a binary string which contanins given number of "0", "1" , "01" and "10" as sub sequences
- Count of adjacent Vowel Consonant Pairs
- Maximize the happiness of the groups on the Trip
- Check whether two strings contain same characters in same order
- Count number of distinct substrings of a given length