972. Equal Rational Numbers
阿新 • • 發佈:2019-01-06
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.
In general a rational number can be represented using up to three parts: an integer part
<IntegerPart>
(e.g. 0, 12, 123)<IntegerPart><.><NonRepeatingPart>
(e.g. 0.5, 1., 2.12, 2.0001)<IntegerPart><.><NonRepeatingPart><(><RepeatingPart><)>
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)
Both 0.1(6) or 0.1666(6) or 0.166(66) are correct representations of 1 / 6.
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) = "".
Note:
- Each part consists only of digits.
- The
<IntegerPart>
will not begin with 2 or more zeros. (There is no other restriction on the digits of each part.) 1 <= <IntegerPart>.length <= 4
0 <= <NonRepeatingPart>.length <= 4
1 <= <RepeatingPart>.length <= 4
思路:把小數展開,沒有迴圈的強行加(0)弄成迴圈,這樣統一處理方便一點。
為了方便處理,儘量多展開一點,下面是展開100次,然後取前90個字元出來比較。需要注意1與0.(9)這種情況
class Solution:
def isRationalEqual(self, S, T):
"""
:type S: str
:type T: str
:rtype: bool
"""
if '.' not in S: S+='.0'
if '.' not in T: T+='.0'
if '(' not in S: S+='(0)'
if '(' not in T: T+='(0)'
idx=S.index('(')
s0=S[:idx]
s1=S[idx+1:len(S)-1]
for _ in range(100):
s0+=s1
idx=T.index('(')
t0=T[:idx]
t1=T[idx+1:len(T)-1]
for _ in range(100):
t0+=t1
s0,t0=s0[:90],t0[:90]
if s0==t0: return True
s=0
while s0[s]==t0[s]: s+=1
if s+1<len(s0) and s0[s+1]=='.': s+=1
fs = len(s0)-s-1
if abs(float(t0)-float(s0))<=float('0.'+'0'*(fs-1)+'1'):
if (s0[s+1:]=='9'*fs and int(t0[s+1:])==0) or (int(s0[s+1:])==0 and t0[s+1:]=='9'*fs):
return True
return False
不太擅長做這種很多邊界的題,很煩,一直debug