sid78669
BAN USERAssuming that all the integers are single digits:
int Evaluate(String str)
{
char [] eqn = str.toCharArray();
int len = str.length;
int rtnVal = -1;
boolean evaluated = false;
int prev = -1;
for(int i = 0; i < len && !evaluted; i++)
{
//Check if the current character is an operator and
//there are more characters following this
if(operator(eqn[i]) && i > 0 && i < (len - 1))
{
int a = prev;
int b = eqn[i+1] - '0'; //fetch the next int
//Evaluate various operations.
switch(eqn[i])
{
case '*':
prev = a*b; //Multiply the previous stored number with the next int
i++; //increment i to cover for the extra int that was used.
break;
case '/':
if(b != 0)
prev = a/b;
else
{
System.Out.Println("Error! Division by zero, TARDIS EXPLODED!!!");
return;
}
i++;
break;
case '+':
//Break the next half of string up to ensure that * and / get
//proper precedence. and add the result to prev.
int b = Evaluate(str.substring(i + 1));
rtnVal = a + b;
//At this point, we have evaluated the string, time to exit.
evaluated = true;
break;
case '-':
int b = Evaluate(str.substring(i + 1));
rtnVal = a - b;
evaluated = true;
break;
}
} else if(i == 0) //Else, if this is the first character, store it in prev.
{
if(checkInt(eqn[i]))
prev = eqn[i] - '0';
else
System.out.println("Error in string.");
}
}
return rtnVal;
}
boolean checkInt(char c)
{
if(c >= '0' && c <= '9')
return true;
else
return false;
}
boolean operator(char c)
{
if(c == '+' || c == '-' || c == '/' || c == '*')
return true;
else
return false;
}
I might have goofed up in the code, but i hope I am able to pass you the idea.
- sid78669 May 21, 2013Although it looks correct (and maybe I am not seeing something), but you might endup having infinite recursion there. In greaterthan, you are reusing greaterthan to compare with 0, and in equatilty you are reusing equality. hence, in either cases (in my silly opinion) you will not hit the case to return false.
However, if I missed something, please point out, I am really interested in the solution to this.
Repannadwilliams31, Applications Developer at National Instruments
I am Anthony, Human Resources specialist with a decade of successful experience in hiring and employee management.I am a ...
Repgarycsroka, Backend Developer at Axiom Sources
Hi I’m Gary, an average 19 year old in a state college who sees life as an adventure.Provide ...
This solution is brilliant. Though, I do have a question. Since a doubly linked list usually has both head and tail pointers, how do we keep the ability of traversing via tail? It seems that we can traverse via head by keeping only one element in the left stack and all of the rest in the right stack, correct?
- sid78669 October 26, 2014