[LeetCode] Equal Rational Numbers

972. Equal Rational Numbers

Given two strings s and t, each of which represents a non-negative rational number, return true if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number.

A rational number can be represented using up to three parts: , , and a . The number will be represented in one of the following three ways:

  • [IntegerPart]

    • For example, 12, 0, and 123.
  • [IntegerPart][.][NonRepeatingPart]

    • For example, 0.5, 1., 2.12, and 123.0001.
  • [IntegerPart][.][NonRepeatingPart][(][RepeatingPart][)]

    • For example, 0.1(6), 1.(9), 123.00(1212).

The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example:

  • 1/6 = 0.16666666… = 0.1(6) = 0.1666(6) = 0.166(66).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Parser {
private:
string front;
string back;

public:
Parser(string s): front(s.substr(0, s.find('.'))) {
const string fill = "00000000";
auto dot = s.find('.');
if(dot == string::npos) {
back = fill;
} else {
auto sof = s.find('(');
if(sof == string::npos) {
back = (s.substr(dot + 1) + fill).substr(0,8);
} else {
string nrPart = s.substr(dot+1, sof-dot-1);
auto eof = s.find(')');
string rPart = s.substr(sof+1, eof-sof-1);
back = nrPart;
for(int i = 0; i < 8; i++) {
back += rPart;
}
back = back.substr(0,8);
}
}
}

bool eq(int f, int b, int of, int ob) {
b = b + 1;
if(b == 100000000) b = 0, f += 1;
return b == ob and f == of;
}

bool eq(Parser* other) {
if(this->front == other->front and this->back == other->back) return true;
int b = stoi(back), ob = stoi(other->back);
int f = stoi(front), of = stoi(other->front);

return eq(f,b,of,ob) || eq(of,ob,f,b);
}
};
class Solution {
public:
bool isRationalEqual(string s, string t) {
Parser* ss = new Parser(s);
Parser* tt = new Parser(t);

return ss->eq(tt);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/31/PS/LeetCode/equal-rational-numbers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.