Skip to content

Instantly share code, notes, and snippets.

@optimistiks
Created January 23, 2024 19:58
Show Gist options
  • Save optimistiks/86f908eac742057a879bbbdf277dffe9 to your computer and use it in GitHub Desktop.
Save optimistiks/86f908eac742057a879bbbdf277dffe9 to your computer and use it in GitHub Desktop.
Given the two integer values of a fraction, numerator and denominator, implement a function that returns the fraction in string format. If the fractional part repeats, enclose the repeating part in parentheses.
export function fractionToDecimal(numerator, denominator){
if (numerator === 0) {
return 0
}
let result = ""
if (numerator < 0 ^ denominator < 0) {
result = "-";
numerator = Math.abs(numerator)
denominator = Math.abs(denominator)
}
const quotient = numerator / denominator
let remainder = (numerator % denominator) * 10
result += toInteger(quotient).toString();
if (remainder === 0) {
return result
}
result += "."
const map = {};
while (remainder != 0) {
const remainderStr = String(remainder)
if (map[remainderStr]) {
const remainderLen = map[remainderStr]
const left = result.substring(0, remainderLen)
const right = result.substring(remainderLen, result.length)
result = left + "(" + right + ")"
return result
}
map[remainderStr] = result.length
const quotient = remainder / denominator
result += toInteger(quotient).toString()
remainder = (remainder % denominator) * 10
}
return result;
}
function toInteger(x) {
x = Number(x);
return x < 0 ? Math.ceil(x) : Math.floor(x);
}
/*
tc: O(pd)
where pd is the lowest denominator we can get after simplifying the expression numerator/denominator
for example, for 8/666 pd=333, for 593/17 pd=17
This is because we will encounter at most pd remainders in our calculations, and therefore,
pd iterations of the loop will be completed in the worst case.
*/
/*
sc: O(pd)
This is because we will encounter at most pd remainders in our calculations,
all of which will need to be stored in the hash map we use to detect the recurrence of remainders.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment