Validation of Equation Given as String | C ++ implementation of the approach ; Function that returns true if the equation is valid ; If it is an integer then add it to another string array ; Evaluation of 1 st operator ; Evaluation of 2 nd operator ; Evaluation of 3 rd operator ; If the LHS result is equal to the RHS ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isValid ( string str ) { int k = 0 ; string operands [ 5 ] = " " ; char operators [ 4 ] ; long ans = 0 , ans1 = 0 , ans2 = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str [ i ] != ' + ' && str [ i ] != ' = ' && str [ i ] != ' - ' ) operands [ k ] += str [ i ] ; else { operators [ k ] = str [ i ] ; if ( k == 1 ) { if ( operators [ k - 1 ] == ' + ' ) ans += stol ( operands [ k - 1 ] ) + stol ( operands [ k ] ) ; if ( operators [ k - 1 ] == ' - ' ) ans += stol ( operands [ k - 1 ] ) - stol ( operands [ k ] ) ; } if ( k == 2 ) { if ( operators [ k - 1 ] == ' + ' ) ans1 += ans + stol ( operands [ k ] ) ; if ( operators [ k - 1 ] == ' - ' ) ans1 -= ans - stol ( operands [ k ] ) ; } if ( k == 3 ) { if ( operators [ k - 1 ] == ' + ' ) ans2 += ans1 + stol ( operands [ k ] ) ; if ( operators [ k - 1 ] == ' - ' ) ans2 -= ans1 - stol ( operands [ k ] ) ; } k ++ ; } } if ( ans2 == stol ( operands [ 4 ] ) ) return true ; else return false ; } int main ( ) { string str = "2 + 5 + 3 + 1 = 11" ; if ( isValid ( str ) ) cout << " Valid " ; else cout << " Invalid " ; return 0 ; }