getting rid of useless stuff for reverse polish notation
Author |
Message |
person
|
Posted: Fri Dec 08, 2006 8:53 pm Post subject: getting rid of useless stuff for reverse polish notation |
|
|
for reverse polish notation (before converting stuff into reverse polish notation), i need to convert an expression from this fromat "-3+(-5(+(+7-2)))" into"(0-3+(0-5((7-2))))" so that the useless + signs are canceled and a "0" is placed in front of a negative number
this task seems easy enough, but the assignment requires me to create a method that performs the function and the method cannot be greater than 3 lines long
here is my shot at it, it's 6 lines long (not counting the brackets and the return statement)
code: |
public class Calculator
{
public static void main (String [] args)
{
String expr = "-3+(-5(+(+7-2)))";
expr = properFormat (expr);
System.out.println (expr);
}
public static String properFormat (String expr)
{
expr = "(" + expr + ")";
for (int i = 1; i < expr.length (); i++)
{
if (expr.charAt (i) == '-' && expr.charAt (i - 1) == '(')
expr = expr.substring (0, i) + "0" + expr.substring (i, expr.length ());
else if
(expr.charAt (i) == '+' && expr.charAt (i - 1) == '(') expr = expr.substring (0, i) + expr.substring (i + 1, expr.length ());
}
return expr;
}
}
|
can anyone give me pointers on how to condense this into 3 lines?[/quote] |
|
|
|
|
|
Sponsor Sponsor
|
|
|
Tony
|
Posted: Fri Dec 08, 2006 9:24 pm Post subject: (No subject) |
|
|
did you loose an extra sign? shouldn't it be
(0-3+(0-5+((7-2))))
possibly with reduction of extra brackets?
Regular Expressions would probably come in handy to cut down the number of lines |
Tony's programming blog. DWITE - a programming contest. |
|
|
|
|
zylum
|
Posted: Fri Dec 08, 2006 11:51 pm Post subject: (No subject) |
|
|
i havent really taken a close look but using the ternary operator will reduce the inner portion of your loop to one line so the whole loop will be one line reducing the whole method to 3 (long) lines.
as tony mentioned, regular expressions can probably shorten your code.
Java: | public static String properFormat (String expr)
{
expr = "(" + expr + ")";
for (int i = 1; i < expr.length (); i++)
expr = (expr.charAt (i) == '-' && expr.charAt (i - 1) == '(') ?
expr.substring (0, i) + "0" + expr.substring (i, expr.length ())
: (expr.charAt (i) == '+' && expr.charAt (i - 1) == '(') ?
expr.substring (0, i) + expr.substring (i + 1, expr.length ()) : expr;
return expr;
} |
|
|
|
|
|
|
|
|