LeetCode in Kotlin

972. Equal Rational Numbers

Hard

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:

The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example:

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:

Solution

class Solution {
    private fun repeat(a: String): String {
        return a.repeat(100)
    }

    fun isRationalEqual(s: String, t: String): Boolean {
        val sLeftIndex = s.indexOf("(")
        val tLeftIndex = t.indexOf("(")

        if (sLeftIndex < 0 && tLeftIndex < 0) {
            return s.toDouble() == t.toDouble()
        }

        var sModified = s
        val sDouble: Double
        if (sLeftIndex >= 0) {
            val repeatingPart = s.substring(sLeftIndex + 1, s.length - 1)
            sModified = s.substring(0, sLeftIndex) + repeat(repeatingPart)

            sDouble = sModified.substring(0, minOf(sModified.length, 100)).toDouble()
        } else {
            sDouble = sModified.toDouble()
        }

        var tModified = t
        val tDouble: Double
        if (tLeftIndex >= 0) {
            val repeatingPart = t.substring(tLeftIndex + 1, t.length - 1)
            tModified = t.substring(0, tLeftIndex) + repeat(repeatingPart)

            tDouble = tModified.substring(0, minOf(tModified.length, 100)).toDouble()
        } else {
            tDouble = tModified.toDouble()
        }

        return sDouble == tDouble
    }
}