|
| 1 | +/** |
| 2 | + * 972. Equal Rational Numbers |
| 3 | + * https://leetcode.com/problems/equal-rational-numbers/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Given two strings s and t, each of which represents a non-negative rational number, return true |
| 7 | + * if and only if they represent the same number. The strings may use parentheses to denote the |
| 8 | + * repeating part of the rational number. |
| 9 | + * |
| 10 | + * A rational number can be represented using up to three parts: <IntegerPart>, <NonRepeatingPart>, |
| 11 | + * and a <RepeatingPart>. The number will be represented in one of the following three ways: |
| 12 | + * - <IntegerPart> |
| 13 | + * - For example, 12, 0, and 123. |
| 14 | + * - <IntegerPart><.><NonRepeatingPart> |
| 15 | + * - For example, 0.5, 1., 2.12, and 123.0001. |
| 16 | + * - <IntegerPart><.><NonRepeatingPart><(><RepeatingPart><)> |
| 17 | + * - For example, 0.1(6), 1.(9), 123.00(1212). |
| 18 | + * |
| 19 | + * The repeating portion of a decimal expansion is conventionally denoted within a pair of round |
| 20 | + * brackets. For example: |
| 21 | + * - 1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66). |
| 22 | + */ |
| 23 | + |
| 24 | +/** |
| 25 | + * @param {string} s |
| 26 | + * @param {string} t |
| 27 | + * @return {boolean} |
| 28 | + */ |
| 29 | +var isRationalEqual = function(s, t) { |
| 30 | + const valueS = parseRational(s); |
| 31 | + const valueT = parseRational(t); |
| 32 | + return Math.abs(valueS - valueT) < 1e-10; |
| 33 | + |
| 34 | + function parseRational(str) { |
| 35 | + const [integer, decimal] = str.split('.'); |
| 36 | + if (!decimal) return parseInt(integer, 10); |
| 37 | + |
| 38 | + const openParen = decimal.indexOf('('); |
| 39 | + if (openParen === -1) return parseInt(integer, 10) + parseFloat(`0.${decimal}`); |
| 40 | + |
| 41 | + const nonRepeating = decimal.slice(0, openParen); |
| 42 | + const repeating = decimal.slice(openParen + 1, -1); |
| 43 | + const nonRepeatValue = nonRepeating ? parseFloat(`0.${nonRepeating}`) : 0; |
| 44 | + const repeatValue = parseInt(repeating, 10) / (10 ** repeating.length - 1) |
| 45 | + / (10 ** nonRepeating.length); |
| 46 | + |
| 47 | + return parseInt(integer, 10) + nonRepeatValue + repeatValue; |
| 48 | + } |
| 49 | +}; |
0 commit comments