18 November 2014

Quiz 50: Solve the equation

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

Input Format: 
Test case number T
Next T lines having an equation

Output Format: 
Solution in each line

Constraints: 
Each operand is single digit number.

Sample Input
3
2+4*8-6
2*2*2-2+8
0+0+0+0+3*2

Sample Output:
-6
32
6

Explanations:
2+4*8-6=2+4*-2=2+-8=-6


Solution:

chomp($t=<STDIN>);
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

2 comments:

  1. I am afraid that your script does not work for two and more digits numbers, e.g.:
    15+2

    ReplyDelete