Class Name: WordCalculator
Method Name: evaluate
Parameters: String
Returns: String
You are to implement a class WordCalculator, which contains a method evaluate.
The method takes a string representing an arithmetic expression you are to
evaluate. The return value of the function is the result of evaluating the
arithmetic expression.
The input expression is structured as follows:
EXPR ::= <NUMBER> <OP> <NUMBER>
OP ::= { "PLUS" | "MINUS" | "TIMES" }
NUMBER ::= ["NEGATIVE "] <POS> |
ZERO
POS ::= <DIGIT> |
<TEEN> |
<PREFIX> ["-" <DIGIT>]
PREFIX ::= NINETY | EIGHTY | SEVENTY | SIXTY | FIFTY | FORTY | THIRTY |
TWENTY
DIGIT ::= ONE | TWO | THREE | FOUR | FIVE | SIX | SEVEN | EIGHT | NINE
TEEN ::= TEN | ELEVEN | TWELVE | THIRTEEN | FOURTEEN | FIFTEEN | SIXTEEN
|
SEVENTEEN | EIGHTEEN | NINETEEN
Some examples of valid inputs are:
NINETY-FOUR MINUS TWELVE
ZERO PLUS SEVENTY-THREE
EIGHTY TIMES NEGATIVE NINETEEN
FOUR PLUS THREE
FOURTEEN MINUS NEGATIVE SIX
Note: Any number whose tens and ones place is over twenty and whose one place
is not zero contains a hyphen. Any number below twenty doesn't have a hyphen.
The output expression is the result of the specified arithmetic operation. The
output expression is structured as follows:
EXPR ::= ["NEGATIVE"] <DIGIT> "THOUSAND" [" " <DIGIT> "HUNDRED"] [" AND
" <POS>] |
["NEGATIVE"] <DIGIT> "HUNDRED" [" AND " <POS>] |
["NEGATIVE"] <POS> |
ZERO
Some examples of valid outputs are:
NINETY-FOUR
NEGATIVE SEVEN THOUSAND AND EIGHT
FOUR THOUSAND EIGHT HUNDRED AND SEVENTY-NINE
ZERO
NEGATIVE TWO THOUSAND FOUR HUNDRED AND THREE
SIX
SEVEN THOUSAND FOUR HUNDRED
Note: The only place the word AND appears in a valid output is when the result
is greater than one hundred and there is a non-zero number in the tens or ones
place.
For input and output, there is at most 1 space between words, and no spaces
around hyphens. The word calculator is case sensitive and all output should be
capital.
The method signature is:
String evaluate(String s)
TopCoder will verify s is a properly formed String, as described above.
Examples:
FORTY-THREE TIMES TWO = EIGHTY-SIX
SEVEN MINUS TWENTY-FOUR = NEGATIVE SEVENTEEN
SIXTY-FOUR TIMES TWELVE = SEVEN HUNDRED AND SIXTY-EIGHT
NEGATIVE FOUR MINUS EIGHT = NEGATIVE TWELVE
NEGATIVE SEVEN PLUS SEVEN = ZERO
ZERO TIMES NEGATIVE NINETY-NINE = ZERO
NEGATIVE SEVENTY-FOUR TIMES NEGATIVE SIXTY-THREE = FOUR THOUSAND SIX HUNDRED
AND SIXTY-TWO
THIRTY-TWO TIMES NEGATIVE SIXTY-THREE = NEGATIVE TWO THOUSAND AND SIXTEEN
|