Solve the Linear Equation of Single Variable | CPP program to solve the given equation ; Function to solve the given equation ; Traverse the equation ; For cases such as : x , - x , + x ; Flip sign once ' = ' is seen ; There may be a number left in the end ; For infinite solutions ; For no solution ; x = total sum / coeff of x ' - ' sign indicates moving numeric value to right hand side ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string solveEquation ( string equation ) { int n = equation . size ( ) , sign = 1 , coeff = 0 ; int total = 0 , i = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( equation [ j ] == ' + ' equation [ j ] == ' - ' ) { if ( j > i ) total += sign * stoi ( equation . substr ( i , j - i ) ) ; i = j ; } else if ( equation [ j ] == ' x ' ) { if ( ( i == j ) equation [ j - 1 ] == ' + ' ) coeff += sign ; else if ( equation [ j - 1 ] == ' - ' ) coeff -= sign ; else coeff += sign * stoi ( equation . substr ( i , j - i ) ) ; i = j + 1 ; } else if ( equation [ j ] == ' = ' ) { if ( j > i ) total += sign * stoi ( equation . substr ( i , j - i ) ) ; sign = -1 ; i = j + 1 ; } } if ( i < n ) total += sign * stoi ( equation . substr ( i ) ) ; if ( coeff == 0 && total == 0 ) return " Infinite ▁ solutions " ; if ( coeff == 0 && total ) return " No ▁ solution " ; int ans = - total / coeff ; return " x = " + to_string ( ans ) ; } int main ( ) { string equation = " x + 5-3 + x = 6 + x - 2" ; cout << solveEquation ( equation ) ; return 0 ; }