Open In App

Validation of Equation Given as String

Last Updated : 11 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string in the form of an equation i.e A + B + C – D = E where A, B, C, D and E are integers and -, + and = are operators. The task is to print Valid if the equation is valid else print Invalid

Note: String only comprises of the characters from the set {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, +, -, =}. 

Examples:

Input: str = “1+1+1+1=7” 
Output: Invalid I

Input: str = “12+13-14+1=12” 
Output: Valid

Approach:

  • Traverse the string and store all the operands in an array operands[] and all the operators in an array operators[].
  • Now perform the arithmetic operation stored in operators[0] on operands[0] and operands[1] and store it in ans.
  • Then perform the seconds arithmetic operation i.e. operators[1] on ans and operators[2] and so on.
  • Finally, compare the ans calculated with the last operand i.e. operands[4]. If they’re equal then print Valid else print Invalid.

Below is the implementation of the above approach: 

C++




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


Java




// Java implementation of the approach
import java.util.*;
 
public class GFG {
 
  // Function that returns true if the equation is valid
  static boolean isValid(String str)
  {
    int k = 0;
    String[] operands = new String[5];
    for (int i = 0; i < 5; i++) {
      operands[i] = "";
    }
 
    char[] operators = new char[4];
    long ans = 0, ans1 = 0, ans2 = 0;
    for (int i = 0; i < str.length(); i++) {
 
      // If it is an integer then add it to another
      // string array
      if (str.charAt(i) != '+' && str.charAt(i) != '='
          && str.charAt(i) != '-')
        operands[k] += str.charAt(i);
      else {
        operators[k] = str.charAt(i);
 
        // Evaluation of 1st operator
        if (k == 1) {
          if (operators[k - 1] == '+')
            ans += Integer.valueOf(
            operands[k - 1])
            + Integer.valueOf(
            operands[k]);
 
          if (operators[k - 1] == '-')
            ans += Integer.valueOf(
            operands[k - 1])
            - Integer.valueOf(
            operands[k]);
        }
 
        // Evaluation of 2nd operator
        if (k == 2) {
          if (operators[k - 1] == '+')
            ans1 += ans
            + Integer.valueOf(
            operands[k]);
 
          if (operators[k - 1] == '-')
            ans1 -= ans
            - Integer.valueOf(
            operands[k]);
        }
 
        // Evaluation of 3rd operator
        if (k == 3) {
          if (operators[k - 1] == '+')
            ans2 += ans1
            + Integer.valueOf(
            operands[k]);
 
          if (operators[k - 1] == '-')
            ans2 -= ans1
            - Integer.valueOf(
            operands[k]);
        }
        k++;
      }
    }
 
    // If the LHS result is equal to the RHS
    if (ans2 == Integer.valueOf(operands[4]))
      return true;
    else
      return false;
  }
 
  // Driver code
  public static void main(String args[])
  {
    String str = "2+5+3+1=11";
    if (isValid(str))
      System.out.print("Valid");
    else
      System.out.print("Invalid");
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Python3




# Python3 implementation of the approach
 
# Function that returns true if
# the equation is valid
def isValid(string) :
     
    k = 0;
    operands = [""] * 5 ;
    operators = [""] * 4 ;
    ans = 0 ; ans1 = 0; ans2 = 0;
    for i in range(len(string)) :
 
        # If it is an integer then add
        # it to another string array
        if (string[i] != '+' and
            string[i] != '=' and
                string[i] != '-') :
            operands[k] += string[i];
        else :
            operators[k] = string[i];
 
            # Evaluation of 1st operator
            if (k == 1) :
                if (operators[k - 1] == '+') :
                    ans += int(operands[k - 1]) + int(operands[k]);
 
                if (operators[k - 1] == '-') :
                    ans += int(operands[k - 1]) - int(operands[k]);
 
            # Evaluation of 2nd operator
            if (k == 2) :
                if (operators[k - 1] == '+') :
                    ans1 += ans + int(operands[k]);
 
                if (operators[k - 1] == '-') :
                    ans1 -= ans - int(operands[k]);
             
 
            # Evaluation of 3rd operator
            if (k == 3) :
                if (operators[k - 1] == '+') :
                    ans2 += ans1 + int(operands[k]);
 
                if (operators[k - 1] == '-') :
                    ans2 -= ans1 - int(operands[k]);
            k += 1
 
    # If the LHS result is equal to the RHS
    if (ans2 == int(operands[4])) :
        return True;
    else :
        return False;
 
 
# Driver code
if __name__ == "__main__" :
 
    string = "2 + 5 + 3 + 1 = 11";
    if (isValid(string)) :
        print("Valid");
    else :
        print("Invalid");
         
# This code is contributed by Ryuga


C#




// C# implementation of the approach
using System;
 
class GFG {
 
  // Function that returns true if the equation is valid
  static bool isValid(string str)
  {
    int k = 0;
    string[] operands = new string[5];
    char[] operators = new char[4];
    long ans = 0, ans1 = 0, ans2 = 0;
    for (int i = 0; i < str.Length; i++) {
 
      // If it is an integer then add it to another
      // string array
      if (str[i] != '+' && str[i] != '='
          && str[i] != '-')
        operands[k] += str[i];
      else {
        operators[k] = str[i];
 
        // Evaluation of 1st operator
        if (k == 1) {
          if (operators[k - 1] == '+')
            ans += Int64.Parse(operands[k - 1])
            + Int64.Parse(operands[k]);
 
          if (operators[k - 1] == '-')
            ans += Int64.Parse(operands[k - 1])
            - Int64.Parse(operands[k]);
        }
 
        // Evaluation of 2nd operator
        if (k == 2) {
          if (operators[k - 1] == '+')
            ans1 += ans
            + Int64.Parse(operands[k]);
 
          if (operators[k - 1] == '-')
            ans1 -= ans
            - Int64.Parse(operands[k]);
        }
 
        // Evaluation of 3rd operator
        if (k == 3) {
          if (operators[k - 1] == '+')
            ans2 += ans1
            + Int64.Parse(operands[k]);
 
          if (operators[k - 1] == '-')
            ans2 -= ans1
            - Int64.Parse(operands[k]);
        }
        k++;
      }
    }
 
    // If the LHS result is equal to the RHS
    if (ans2 == Int64.Parse(operands[4]))
      return true;
    else
      return false;
  }
 
  // Driver code
  public static void Main()
  {
    string str = "2+5+3+1=11";
    if (isValid(str))
      Console.Write("Valid");
    else
      Console.Write("Invalid");
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript




<script>
// Javascript implementation of the approach
 
// Function that returns true if the equation is valid
function isValid(str)
{
    let k = 0;
    let operands = [];
    for (let i = 0; i < 5; i++) {
      operands[i] = "";
    }
     
    let operators = []
    let ans = 0;
    let ans1 = 0;
    let ans2 = 0;
    for (let i = 0; i < str.length; i++) {
 
      // If it is an integer then add it to another
      // string array
      if (str[i] != '+' && str[i] != '=' && str[i] != '-')
        operands[k] += str[i];
      else {
        operators[k] = str[i];
 
        // Evaluation of 1st operator
        if (k == 1) {
          if (operators[k - 1] == '+')
            ans += parseInt(operands[k - 1]) + parseInt(operands[k]);
 
          if (operators[k - 1] == '-')
            ans += parseInt(operands[k - 1]) - parseInt(operands[k]);
        }
 
        // Evaluation of 2nd operator
        if (k == 2) {
          if (operators[k - 1] == '+')
            ans1 += ans + parseInt(operands[k]);
 
          if (operators[k - 1] == '-')
            ans1 -= ans - parseInt(operands[k]);
        }
 
        // Evaluation of 3rd operator
        if (k == 3) {
          if (operators[k - 1] == '+')
            ans2 += ans1 + parseInt(operands[k]);
 
          if (operators[k - 1] == '-')
            ans2 -= ans1 - parseInt(operands[k]);
        }
        k++;
      }
    }
 
    // If the LHS result is equal to the RHS
    if (ans2 == parseInt(operands[4]))
        return true;
    else
        return false;
}
 
// Driver code
let str = "2+5+3+1=11";
if (isValid(str))
    document.write("Valid");
else
    document.write("Invalid");
 
// This code is contributed by Samim Hossain Mondal.
</script>


Output

Valid

Time Complexity: O(n), where n is the length of the given string.
Auxiliary Space: O(1), no extra space is required, so it is a constant.



Similar Reads

Quadratic equation whose roots are reciprocal to the roots of given equation
Given three integers A, B, and C representing the coefficients of a quadratic equation Ax2 + Bx + C = 0, the task is to find the quadratic equation whose roots are reciprocal to the roots of the given equation. Examples: Input: A = 1, B = -5, C = 6 Output: (6)x^2 +(-5)x + (1) = 0Explanation: The given quadratic equation x2 - 5x + 6 = 0.Roots of the
4 min read
Quadratic equation whose roots are K times the roots of given equation
Given three integers A, B, and C representing the coefficients of a quadratic equation Ax2 + Bx + C = 0 and a positive integer K, the task is to find the coefficients of the quadratic equation whose roots are K times the roots of the given equation. Examples: Input: A = 1, B = 2, C = 1, K = 2Output: 1 4 4Explanation:The given quadratic equation x2
4 min read
Draw circle using polar equation and Bresenham's equation
In this article, we will discuss how to draw circles using Bresenham Equation and Polar Equation. Circle Drawing AlgorithmIt is not easy to display a continuous smooth arc on the computer screen as our computer screen is made of pixels organized in matrix form. So, to draw a circle on a computer screen it should always choose the nearest pixels fro
19 min read
Given equation of a circle as string, find area
Given an equation of the circle X2 + Y2 = R2 whose center at origin (0, 0) and the radius is R. The task is to find area of circle. Examples : Input : X*X + Y*Y = 25Output : The area of circle centered at origin is : 78.55 Input : X*X + Y*Y = 64Output : The area of circle centered at origin is : 201.088 Approach: Given an equation X2 + Y2 = R2 and
7 min read
Equation of a straight line passing through a point and making a given angle with a given line
Given four integers a, b, c representing coefficients of a straight line with equation (ax + by + c = 0), the task is to find the equations of the two straight lines passing through a given point [Tex](x1, y1) [/Tex]and making an angle ? with the given straight line. Examples: Input: a = 2, b = 3, c = -7, x1 = 4, y1 = 9, ? = 30Output: y = -0.49x +1
16 min read
Find the missing value from the given equation a + b = c
Given an equation of the form: a + b = c Out of which any one of the terms [Tex]a [/Tex], [Tex]b [/Tex]or [Tex]c [/Tex]is missing. The task is to find the missing term. Examples: Input: 2 + 6 = ? Output: 8 Input: ? + 3 =6 Output: 3 Approach: Missing numbers can be found simply using the equation [Tex]a + b = c [/Tex]. First, we will find two known
7 min read
Find the number of solutions to the given equation
Given three integers A, B and C, the task is to find the count of values of X such that the following condition is satisfied, X = B * Sm(X)A + C where Sm(X) denotes the sum of digits of X and 1 &lt; X &lt; 109.Examples: Input: A = 3, B = 2, C = 8 Output: 3 For X = 10, 2 * (1)3 + 8 = 10 For X = 2008, 2 * (10)3 + 8 = 2008 For X = 13726, 2 * (19)3 + 8
6 min read
Equation of straight line passing through a given point which bisects it into two equal line segments
Given a straight line which passes through a given point (x0, y0) such that this point bisects the line segment in two equal line segments. The task is to find the equation of this straight line.Examples: Input: x0 = 4, y0 = 3 Output: 3x + 4y = 24Input: x0 = 7, y0 = 12 Output: 12x + 7y = 168 Approach: Let PQ be the line and AB be the line segment b
4 min read
Count of triplets that satisfy the given equation
Given an array arr[] of N non-negative integers. The task is to count the number of triplets (i, j, k) where 0 ? i &lt; j ? k &lt; N such that A[i] ^ A[i + 1] ^ ... ^ A[j - 1] = A[j] ^ A[j + 1] ^ ... ^ A[k] where ^ is the bitwise XOR.Examples: Input: arr[] = {2, 5, 6, 4, 2} Output: 2 The valid triplets are (2, 3, 4) and (2, 4, 4).Input: arr[] = {5,
5 min read
Find the quadratic equation from the given roots
Given the roots of a quadratic equation A and B, the task is to find the equation.Note: The given roots are integral. Examples: Input: A = 2, B = 3 Output: x^2 - (5x) + (6) = 0 x2 - 5x + 6 = 0 x2 -3x -2x + 6 = 0 x(x - 3) - 2(x - 3) = 0 (x - 3) (x - 2) = 0 x = 2, 3 Input: A = 5, B = 10 Output: x^2 - (15x) + (50) = 0 Approach: If the roots of a quadr
4 min read
Article Tags :
Practice Tags :