Find the missing digit x from the given expression
Given an alphanumeric string, consisting of a single alphabet X, which represents an expression of the form:
A operator B = C
where A, B and C denotes integers and the operator can be either of +, -, * or /
The task is to evaluate the missing digit X present in any of the integers A, B and C such that the given expression holds to be valid.
Input: S = “3x + 12 = 46”
If we subtract 12 from 46, we will get 34.
So, on comparing 3x and 34. the value of x = 4
Input: S = “4 – 2 = x”
After solving the equation, the value of x = 2.
Approach: Follow the steps below to solve the problem:
- Split the string to extract the two operands, operator and the resultant.
- Check if X is present in the resultant or not. If so, then compute the value of the resultant by applying operations on the first operand and second operand with the operator.
- Otherwise, if X is not present in the resultant. Then check if X is present in the first operand. If so, then apply the operation on the second operand and resultant with the operator.
- Otherwise, if X is not present in the first operand also. Then check if X is present in the second operand. If so, then apply the operation on the first operand and resultant with the operator.
Below is the implementation of the above approach:
Time Complexity: O(L), where is the length of the equation.
Auxiliary Space: O(1)
Attention reader! All those who say programming isn’t for kids, just haven’t met the right mentors yet. Join the Demo Class for First Step to Coding Course, specifically designed for students of class 8 to 12.
The students will get to learn more about the world of programming in these free classes which will definitely help them in making a wise career choice in the future.