Algorithm


Problem Name: 972. Equal Rational Numbers

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:

  • <IntegerPart>
    • For example, 12, 0, and 123.
  • <IntegerPart><.><NonRepeatingPart>
    • For example, 0.5, 1., 2.12, and 123.0001.
  • <IntegerPart><.><NonRepeatingPart><(><RepeatingPart><)>
    • For example, 0.1(6), 1.(9), 123.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).

 

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:

  • Each part consists only of digits.
  • The <IntegerPart> does not have leading zeros (except for the zero itself).
  • 1 <= <IntegerPart>.length <= 4
  • 0 <= <NonRepeatingPart>.length <= 4
  • 1 <= <RepeatingPart>.length <= 4

Code Examples

#1 Code Example with Javascript Programming

Code - Javascript Programming


const isRationalEqual = function (S, T) {
  return f(S) === f(T)
}

function f(S) {
  let i = S.indexOf('(')
  if (i > 0) {
    let base = S.slice(0, i)
    let rep = S.slice(i + 1, S.length - 1)
    for (let j = 0; j  <  20; ++j) base += rep
    return +base
  }
  return +S
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "0.(52)", t = "0.5(25)"

Output

x
+
cmd
true

#2 Code Example with Python Programming

Code - Python Programming


class Solution:
    def isRationalEqual(self, S, T):
        def f(s):
            i = s.find('(')
            if i >= 0:
                s = s[:i] + s[i + 1:-1] * 20
            return float(s[:20])
        return f(S) == f(T)
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "0.(52)", t = "0.5(25)"

Output

x
+
cmd
true
Advertisements

Demonstration


Previous
#971 Leetcode Flip Binary Tree To Match Preorder Traversal Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#973 Leetcode K Closest Points to Origin Solution in C, C++, Java, JavaScript, Python, C# Leetcode