- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 30 lines of C++ from the credited upstream file 972.cpp.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 bool isRationalEqual(string s, string t) {4 return abs(valueOf(s) - valueOf(t)) < 1e-9;5 }6 7 private:8 const vector<double> ratios{1.0, 1.0 / 9, 1.0 / 99, 1.0 / 999, 1.0 / 9999};9 10 double valueOf(const string& s) {11 if (s.find('(') == string::npos)12 return stod(s);13 14 15 const int leftParenIndex = s.find_first_of('(');16 const int rightParenIndex = s.find_first_of(')');17 const int dotIndex = s.find_first_of('.');18 19 20 const double integerAndNonRepeating = stod(s.substr(0, leftParenIndex));21 const int nonRepeatingLength = leftParenIndex - dotIndex - 1;22 23 24 const int repeating = stoi(s.substr(leftParenIndex + 1, rightParenIndex));25 const int repeatingLength = rightParenIndex - leftParenIndex - 1;26 return integerAndNonRepeating +27 repeating * pow(0.1, nonRepeatingLength) * ratios[repeatingLength];28 }29};30