# Solve the equation

Problem to find the x value in given equation. The equation perform the arithmatic operation "+" and "-" only.

## Example-1:

Input    : n = "x+5=10"
Output   : 5
Explain  : x + 5 = 10
x = 10-5
x = 5

## Example-2:

Input    : n = "10+5=-x+2"
Output   : -13
Explain  : 10+5=-x+2
10+5-2=-x
13=-x
x=-13

## Example-3:

Input    : n = "1+2=-2+4+x"
Output   : 1
Explain  : 1+2=-2+4+x
3-2=x
x=1

# Solution

public class Main
{
public static void main(String[] args)
{
String s = "10+5=-x+2";

int value = 0;

boolean f = false, x_lhs = false;

for (int i=0;i<s.length();i++)
{
if(isNum(s.charAt(i)))
{
int a = 0;

if(i != 0 && s.charAt(i-1)=='-')
{
while(i<s.length() && isNum(s.charAt(i)))
{
a = (a*10) + Character.getNumericValue(s.charAt(i));

i++;
}

if(f) value = value + a;

else
{
value = value-a;
}
}

else
{
while(i<s.length()&&isNum(s.charAt(i)))
{
a = (a*10) + Character.getNumericValue(s.charAt(i));

i++;
}

if(f) value = value-a;

else
{
value = value + a;
}

}

i--;
}

if(s.charAt(i)=='=') f = true;

if(!f&&s.charAt(i)=='x')
{
x_lhs = true;

if(i!=0&&s.charAt(i-1)=='-') x_lhs = false;

}

if(f&&s.charAt(i)=='x'&&s.charAt(i-1)=='-') x_lhs=true;

}

if(x_lhs) System.out.println(-value);

else
{
System.out.println(value);
}
}

public static boolean isNum(char c)
{
if(c >= '0' && c<='9') return true;

return false;
}
}

5