-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0972-equal-rational-numbers.js
More file actions
56 lines (44 loc) · 1.71 KB
/
0972-equal-rational-numbers.js
File metadata and controls
56 lines (44 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
* Equal Rational Numbers
* Time Complexity: O(L)
* Space Complexity: O(L)
*/
var isRationalEqual = function (s, t) {
const firstValueConverted = convertDecimalToFloat(s);
const secondValueConverted = convertDecimalToFloat(t);
const toleranceThreshold = 1e-10;
return (
Math.abs(firstValueConverted - secondValueConverted) < toleranceThreshold
);
function convertDecimalToFloat(inputRepresentation) {
const partsOfNumber = inputRepresentation.split(".");
const integerPartStr = partsOfNumber[0];
const parsedInteger = parseInt(integerPartStr, 10);
if (partsOfNumber.length === 1) {
return parsedInteger;
}
const fractionalPartStr = partsOfNumber[1];
const parenthesisPosition = fractionalPartStr.indexOf("(");
if (parenthesisPosition === -1) {
const nonRepeatingDecimalStr = `0.${fractionalPartStr}`;
const nonRepeatingDecimalVal = parseFloat(nonRepeatingDecimalStr);
return parsedInteger + nonRepeatingDecimalVal;
}
const preRepeatDigits = fractionalPartStr.slice(0, parenthesisPosition);
const cycleDigits = fractionalPartStr.slice(
parenthesisPosition + 1,
fractionalPartStr.length - 1,
);
let preRepeatNumeric = 0;
if (preRepeatDigits.length > 0) {
const decimalForPreRepeat = `0.${preRepeatDigits}`;
preRepeatNumeric = parseFloat(decimalForPreRepeat);
}
const cycleNumeric = parseInt(cycleDigits, 10);
const cycleDenominator = Math.pow(10, cycleDigits.length) - 1;
const preRepeatPowerShift = Math.pow(10, preRepeatDigits.length);
const cycleContribution =
cycleNumeric / cycleDenominator / preRepeatPowerShift;
return parsedInteger + preRepeatNumeric + cycleContribution;
}
};