Problem
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
Example 1:
Input: numerator = 1, denominator = 2
Output: "0.5"
Example 2:
Input: numerator = 2, denominator = 1
Output: "2"
Example 3:
Input: numerator = 2, denominator = 3
Output: "0.(6)"
Solution
/**
* @param {number} numerator
* @param {number} denominator
* @return {string}
*/
var fractionToDecimal = function(numerator, denominator) {
if (denominator === 0) return 'NaN';
var sign = numerator !== 0 && ((numerator > 0) ^ (denominator > 0));
var num = Math.abs(numerator);
var de = Math.abs(denominator);
var result = sign ? '-' : '';
var map = {};
result += Math.floor(num / de);
num %= de;
if (num === 0) return result;
result += '.';
while (num > 0) {
num *= 10;
if (map[num] !== undefined) {
result = result.substr(0, map[num]) + '(' + result.substr(map[num]) + ')';
break;
} else {
map[num] = result.length;
}
result += Math.floor(num / de);
num %= de;
}
return result;
};
Explain:
nope.
Complexity:
- Time complexity : O(n).
- Space complexity : O(n).