Problem:
Given a equation with operations +,-,* only, You have to find the answer.
Start reading the equation from the right and move towards the left.
So, 1*2+3=>1*5=>5
Start reading the equation from the right and move towards the left.
So, 1*2+3=>1*5=>5
Input Format:
Test case number T
Next T lines having an equation
Next T lines having an equation
Output Format:
Solution in each line
Solution in each line
Constraints:
Each operand is single digit number.
Each operand is single digit number.
Sample Input
3
2+4*8-6
2*2*2-2+8
0+0+0+0+3*2
2+4*8-6
2*2*2-2+8
0+0+0+0+3*2
Sample Output:
-6
32
6
-6
32
6
Explanations:
2+4*8-6=2+4*-2=2+-8=-6
2+4*8-6=2+4*-2=2+-8=-6
Solution:
for($i=0;$i<$t;$i++)
{
chomp($tmp=<STDIN>);
@arr=split(//,$tmp);
$len=@arr;
if($len == 1)
{
push(@out,$arr[0]);
next;
}
$len--;
for($j=$len;$j>=0;$j--)
{
($a,$b,$c)=($arr[$j],$arr[$j-1],$arr[$j-2]);
if($b eq '+')
{
$ans=$a+$c;
}
elsif($b eq '-')
{
$ans=$a-$c;
}
if($b eq '*')
{
$ans=$a*$c;
}
$arr[$j-2]=$ans;
$j--;
}
push(@out,$a);
}
foreach(@out)
{
print "$_\n";
}
Tips:
operate 3 elements of array, get result , then operation it with next 2 elements and so on
I am afraid that your script does not work for two and more digits numbers, e.g.:
ReplyDelete15+2
Good catch, updated constraints.
Delete