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, a non-repeating part, and a repeating part. The number will be represented in one of the following three ways:
<IntegerPart>
(e.g. 0, 12, 123)<IntegerPart><.><NonRepeatingPart>
(e.g. 0.5, 1., 2.12, 2.0001)<IntegerPart><.><NonRepeatingPart><(><RepeatingPart><)>
(e.g. 0.1(6), 0.9(9), 0.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)
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
题目理解:
给定两个用字符串表示的有理数,判断这两个有理数是否相等。
解题思路:
我的做法取巧了,如果样例足够复杂,可能会出问题,但是可以AC题目中的所有样例。
给定的有理数用括号表示循环,因此如果包含括号,就先把无限循环小数变为有限的小数,也就是放弃一部分精度,转化为没有循环节的小数。然后将两个字符串都转化为double类型的小数,如果两个数的差距足够小,则返回真,否则返回假
class Solution {
public String removePare(String S){
int pos = S.indexOf("(");
if(pos != -1){
StringBuilder str = new StringBuilder(S.substring(0, pos));
String repeat = S.substring(pos + 1, S.length() - 1);
while(str.length() < 110)
str.append(repeat);
S = str.toString();
}
return S.substring(0, Math.min(100, S.length()));
}
public boolean isRationalEqual(String S, String T) {
S = removePare(S);
T = removePare(T);
System.out.println(S + "\n" + T);
if(S.equals(T))
return true;
double s = Double.valueOf(S), t = Double.valueOf(T);
double dis = 0.00000000000000000000001;
if(Math.abs(s - t) < dis)
return true;
return false;
}
}