Equal Rational Numbers Problem


Description

LeetCode Problem 972.

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: , , and a . The number will be represented in one of the following three ways:

  • For example, 12, 0, and 123.
  • <.>
  • For example, 0.5, 1., 2.12, and 123.0001.
  • <.><(><)>
  • 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:

1
2
3
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:

1
2
Input: s = "0.1666(6)", t = "0.166(66)"
Output: true

Example 3:

1
2
3
4
Input: s = "0.9(9)", t = "1."
Output: true
Explanation: "0.9(9)" represents 0.999999999... repeated forever, which equals 1.  [<a href="https://en.wikipedia.org/wiki/0.999..." target="_blank">See this link for an explanation.</a>]
"1." represents the number 1, which is formed correctly: (IntegerPart) = "1" and (NonRepeatingPart) = "".

Constraints:

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


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
    // Transform string to double
    bool isRationalEqual(string S, string T) {
        return f(S) == f(T);
    }
    double f(string S) {
        auto i = S.find("(");
        if (i != string::npos) {
            string base = S.substr(0, i);
            string rep = S.substr(i + 1, S.length() - i - 2);
            for (int j = 0; j < 20; ++j) 
                base += rep;
            return stod(base);
        }
        return stod(S);
    }
};




Related Posts

Three Equal Parts Problem

LeetCode 927. You are given an array arr which consists...

Surface Area Of 3D Shapes Problem

LeetCode 892. You are given an n x n grid...

Super Palindromes Problem

LeetCode 906. Let’s say a positive integer is a super-palindrome...

Smallest Range I Problem

LeetCode 908. You are given an integer array nums and...

Projection Area Of 3D Shapes Problem

LeetCode 883. You are given an n x n grid...

Prime Palindrome Problem

LeetCode 866. Given an integer n, return the smallest prime...