972. Equal Rational Numbers
Description
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: <IntegerPart>
, <NonRepeatingPart>
, and a <RepeatingPart>
. The number will be represented in one of the following three ways:
<IntegerPart>
- For example,
12
,0
, and123
.
- For example,
<IntegerPart><.><NonRepeatingPart>
- For example,
0.5
,1.
,2.12
, and123.0001
.
- For example,
<IntegerPart><.><NonRepeatingPart><(><RepeatingPart><)>
- For example,
0.1(6)
,1.(9)
,123.00(1212)
.
- For example,
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)
.
Example 1:
Input: s = "0.(52)", t = "0.5(25)" Output: true Explanation: Because "0.(52)" represents 0.52525252..., and "0.5(25)" represents 0.52525252525..... , the strings represent the same number.
Example 2:
Input: s = "0.1666(6)", t = "0.166(66)" Output: true
Example 3:
Input: s = "0.9(9)", t = "1." Output: true Explanation: "0.9(9)" represents 0.999999999... repeated forever, which equals 1. [See this link for an explanation.] "1." represents the number 1, which is formed correctly: (IntegerPart) = "1" and (NonRepeatingPart) = "".
Constraints:
- Each part consists only of digits.
- The
<IntegerPart>
does not have leading zeros (except for the zero itself). 1 <= <IntegerPart>.length <= 4
0 <= <NonRepeatingPart>.length <= 4
1 <= <RepeatingPart>.length <= 4
Solution
equal-rational-numbers.py
class Solution:
def isRationalEqual(self, s: str, t: str) -> bool:
def g(s):
s2 = ""
rep1 = ""
ok = False
for x in s:
if x == "(" or x == ")":
ok = True
continue
if ok:
rep1 += x
else:
s2 += x
return (s2, rep1)
os1, rep1 = g(s)
os2, rep2 = g(t)
s1 = os1 + rep1 * 30
s2 = os2 + rep2 * 30
if len(rep1) == 0 and len(rep2) == 0:
return s1 == s2 or float(s1) == float(s2)
if s1 == s2 or float(s1) == float(s2): return True
def good(s1, s2):
count = 1
curr = s1[-1]
roundCount = len(s2) - 2
for i in range(len(s1) - 2, -1, -1):
if curr == s1[i]:
count += 1
else:
return False
if i > 0 and s1[i] != s1[i - 1] and count >= 30:
ss = s1[:i + 1]
r = float(ss) + float("0." + "0" * (len(ss) - 3 - bool(s1[i - 1] == ".")) + "1")
if r == float(s2):
return True
return False
return good(s1, s2) or good(s2, s1)