LeetCode Solutions

972. Equal Rational Numbers

Time:

Space:

			

class Solution {
 public:
  bool isRationalEqual(string S, string T) {
    return abs(valueOf(S) - valueOf(T)) < 1e-9;
  }

 private:
  vector<double> ratios{1.0, 1.0 / 9, 1.0 / 99, 1.0 / 999, 1.0 / 9999};

  double valueOf(const string& s) {
    if (s.find('(') == string::npos)
      return stod(s);

    double integer_nonRepeating = stod(s.substr(0, s.find_first_of('(')));
    int nonRepeatingLength = s.find_first_of('(') - s.find_first_of('.') - 1;
    int repeating =
        stoi(s.substr(s.find_first_of('(') + 1, s.find_first_of(')')));
    int repeatingLength = s.find_first_of(')') - s.find_first_of('(') - 1;

    return integer_nonRepeating +
           repeating * pow(0.1, nonRepeatingLength) * ratios[repeatingLength];
  }
};
			

class Solution {
  public boolean isRationalEqual(String S, String T) {
    return Math.abs(valueOf(S) - valueOf(T)) < 1e-9;
  }

  private double[] ratios = new double[] {1.0, 1.0 / 9, 1.0 / 99, 1.0 / 999, 1.0 / 9999};

  private double valueOf(final String s) {
    if (!s.contains("("))
      return Double.valueOf(s);

    double integer_nonRepeating = Double.valueOf(s.substring(0, s.indexOf('(')));
    int nonRepeatingLength = s.indexOf('(') - s.indexOf('.') - 1;
    int repeating = Integer.parseInt(s.substring(s.indexOf('(') + 1, s.indexOf(')')));
    int repeatingLength = s.indexOf(')') - s.indexOf('(') - 1;

    return integer_nonRepeating +
        repeating * Math.pow(0.1, nonRepeatingLength) * ratios[repeatingLength];
  }
}
			

class Solution:
  def isRationalEqual(self, S: str, T: str) -> bool:
    def valueOf(s: str) -> float:
      if s.find('(') == -1:
        return float(s)

      integer_nonRepeating = float(s[:s.find('(')])
      nonRepeatingLength = s.find('(') - s.find('.') - 1
      repeating = float(s[s.find('(') + 1: s.find(')')])
      repeatingLength = s.find(')') - s.find('(') - 1

      return integer_nonRepeating + repeating * 0.1**nonRepeatingLength * ratios[repeatingLength]

    ratios = [1, 1 / 9, 1 / 99, 1 / 999, 1 / 9999]

    return abs(valueOf(S) - valueOf(T)) < 1e-9