Skip to content

Commit 1c5b916

Browse files
committed
Update Solution.kt
1 parent 77f0321 commit 1c5b916

File tree

1 file changed

+34
-14
lines changed
  • src/main/kotlin/g0901_1000/s0972_equal_rational_numbers

1 file changed

+34
-14
lines changed

src/main/kotlin/g0901_1000/s0972_equal_rational_numbers/Solution.kt

Lines changed: 34 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,41 @@ package g0901_1000.s0972_equal_rational_numbers
22

33
// #Hard #String #Math #2023_05_06_Time_130_ms_(100.00%)_Space_35.4_MB_(50.00%)
44

5-
import kotlin.math.abs
6-
import kotlin.math.pow
7-
85
class Solution {
9-
fun isRationalEqual(s: String, t: String): Boolean {
10-
return abs(valueOf(s) - valueOf(t)) < 1e-9
6+
private fun repeat(a: String): String {
7+
return a.repeat(100)
118
}
12-
private val ratios = doubleArrayOf(1.0, 1.0 / 9, 1.0 / 99, 1.0 / 999, 1.0 / 9999)
13-
private fun valueOf(s: String): Double {
14-
if (!s.contains("(")) return java.lang.Double.valueOf(s)
15-
val integerNonRepeating = java.lang.Double.valueOf(s.substring(0, s.indexOf('(')))
16-
val nonRepeatingLength = s.indexOf('(') - s.indexOf('.') - 1
17-
val repeating = s.substring(s.indexOf('(') + 1, s.indexOf(')')).toInt()
18-
val repeatingLength = s.indexOf(')') - s.indexOf('(') - 1
19-
return integerNonRepeating +
20-
repeating * 0.1.pow(nonRepeatingLength.toDouble()) * ratios[repeatingLength]
9+
10+
fun isRationalEqual(s: String, t: String): Boolean {
11+
val sLeftIndex = s.indexOf("(")
12+
val tLeftIndex = t.indexOf("(")
13+
14+
if (sLeftIndex < 0 && tLeftIndex < 0) {
15+
return s.toDouble() == t.toDouble()
16+
}
17+
18+
var sModified = s
19+
val sDouble: Double
20+
if (sLeftIndex >= 0) {
21+
val repeatingPart = s.substring(sLeftIndex + 1, s.length - 1)
22+
sModified = s.substring(0, sLeftIndex) + repeat(repeatingPart)
23+
24+
sDouble = sModified.substring(0, minOf(sModified.length, 100)).toDouble()
25+
} else {
26+
sDouble = sModified.toDouble()
27+
}
28+
29+
var tModified = t
30+
val tDouble: Double
31+
if (tLeftIndex >= 0) {
32+
val repeatingPart = t.substring(tLeftIndex + 1, t.length - 1)
33+
tModified = t.substring(0, tLeftIndex) + repeat(repeatingPart)
34+
35+
tDouble = tModified.substring(0, minOf(tModified.length, 100)).toDouble()
36+
} else {
37+
tDouble = tModified.toDouble()
38+
}
39+
40+
return sDouble == tDouble
2141
}
2242
}

0 commit comments

Comments
 (0)