MathDebug
SRM 94 · 2002-06-01 · by brett1479
Problem Statement
You are writing the embedded software to make sure a calculator functions properly. This is a special calculator that allows simple arithmetic with very large integers. The following rules are in place for PROPER USAGE (quotes used for clarity):
1) A valid calculation consists of <NUMBER><OPERATOR><NUMBER><EQUALS> where:
- <NUMBER> is a string of one or more digits('0'..'9')
- <OPERATOR> is one of '+','-','*','/'
- <EQUALS> is '='
2) The calculator can perform a sequence of valid calculations in a row.
- So 98+01234=234*1230=000/000= is valid where
- 98+01234= is the first calculation,
- 234*1230= is the second and
- 000/000= is the last.
Embedded logic is needed to determine what the next key-press should be. Your function will return what key-press the calculator can accept next according to the following schema (quotes used for clarity):
Next key-press : Return
--------------------------------------------------------
Digit ('0'..'9') : 1
Operator ('+','-','*','/') : 2
Digit or Operator ('0'..'9','+','-','*','/') : 3
Equals ('=') : 4
Digit or Equals ('0'..'9','=') : 5
For example, if you have:
"47"
The next key-press could either be a Digit or an Operator so you would return 3.
If the input given doesn't follow the above laws of PROPER USAGE you should
return 0. This means that invalid key-presses occurred previously and your
calculator is no longer in a functioning state. For example, if you have:
"53++6=12+"
The input has 2 consecutive Operator key-presses("++") so the entire input
violates PROPER USAGE and you will return 0.
Create a class MathDebug that contains the method getNext, which takes a
Constraints
- input will only contain characters within the following string: "0123456789+-*/=" (quotes are for clarity).
- input will have length between 0 and 50 characters, inclusive.
"*" Returns: 0
"54+6564=465/546=565" Returns: 3
"" Returns: 1
"123" Returns: 3
"123+456" Returns: 5
"1+2=" Returns: 1
Thus far we have which is one valid calculation. We can now accept another valid calculation of the form . Since is next we will only accept a Digit key-press.
"123+" Returns: 1
Thus far we have so we need the next . The only possible key-press is Digit since if, Equal was given, the second would have a length of 0.
"" Returns: 1
No input has been given thus far so we are waiting for a Digit key-press.
"1" Returns: 3
The next key-press could be either a Digit or an Operator.
"=123+456=" Returns: 0
The input started with an '=' which is an invalid key-press so the entire computation is invalid.
Submissions are judged against all 42 archived test cases, of which 10 are shown here. Case numbers match the judge’s.
Language: C++17 · define a public class MathDebug with a public method int getNext(string input) · 42 test cases · 2 s / 256 MB per case