String hello = "44+"
int result=0, top=-1;
int []stack = new int[hello.length()];
for(int i=0 ; i<hello.length() ; i++)
{
char c = s.charAt(i);
if(c >= '0' && c <= '9')
stack[++top]=(int)(c-'0');
else
{
int x=stack[top--]; //pop
int y=stack[top--]; //pop
switch(c)
{
case '+' : result = x + y;
break;
case '-' : result = y - x;
break;
case '*' : result = x * y;
break;
case '/' : result = y / x;
break;
default : result = 0;
}
stack[++top]=result; //push
}
}
result = stack[top--]; //pop
return result;
44+ stores 8 -> return result happens and when I print it on the main I get 8 as a output.. which is correct
if I replace this code
stack[++top]=(int)(c-'0');
with this one
stack[++top]=(int)(c);
the output looks like this = 104.. the second code looks correct to me but it doesn't give me the correct output
My questions are
- why
c-'0'
is used and not ac
only ? - why
case '-' : result = y - x
is used and notx - y
? - why
case '/' : result = y / x
is used and notx / y
?
Thanks in advance