Skip to content

Commit f776b85

Browse files
authored
Create solution.java
solution in java
1 parent eef5794 commit f776b85

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
public boolean isRationalEqual(String s, String t) {
3+
return Math.abs(valueOf(s) - valueOf(t)) < 1e-9;
4+
}
5+
6+
private static double[] ratios = new double[] {1.0, 1.0 / 9, 1.0 / 99, 1.0 / 999, 1.0 / 9999};
7+
8+
private double valueOf(final String s) {
9+
if (!s.contains("("))
10+
return Double.valueOf(s);
11+
12+
// Get the indices..
13+
final int leftParenIndex = s.indexOf('(');
14+
final int rightParenIndex = s.indexOf(')');
15+
final int dotIndex = s.indexOf('.');
16+
17+
// integerAndNonRepeating := <IntegerPart><.><NonRepeatingPart>
18+
final double nonRepeating = Double.valueOf(s.substring(0, leftParenIndex));
19+
final int nonRepeatingLength = leftParenIndex - dotIndex - 1;
20+
21+
// repeating := <RepeatingPart>
22+
final int repeating = Integer.parseInt(s.substring(leftParenIndex + 1, rightParenIndex));
23+
final int repeatingLength = rightParenIndex - leftParenIndex - 1;
24+
return nonRepeating + repeating * Math.pow(0.1, nonRepeatingLength) * ratios[repeatingLength];
25+
}
26+
}

0 commit comments

Comments
 (0)