166. Fraction to Recurring Decimal
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to convert a fraction, given as a numerator and a denominator, into its string representation. The key challenges are:
Solution
Fraction to Recurring Decimal in Python
class Solution:
def fractionToDecimal(self, numerator: int, denominator: int) -> str:
# Handle the case where numerator is 0.
if numerator == 0:
return "0"
res = []
# Determine the sign. If signs are different, the result is negative.
if (numerator > 0) != (denominator > 0):
res.append("-")
# Work with absolute values. Python integers handle arbitrary size, so no overflow.
num, den = abs(numerator), abs(denominator)
# Append the integer part.
res.append(str(num // den))
remainder = num % den
# If there's no fractional part, we are done.
if remainder == 0:
return "".join(res)
# Append the decimal point.
res.append(".")
# Use a dictionary to store remainders and their positions.
# Key: remainder, Value: index in the result list where this remainder first occurred.
remainder_map = {}
while remainder != 0:
# If the remainder has been seen before, we found a repeating cycle.
if remainder in remainder_map:
# Get the index where the cycle starts.
start_index = remainder_map[remainder]
# Insert '(' at the start of the repeating part.
res.insert(start_index, "(")
# Append ')' at the end.
res.append(")")
break
# Store the remainder and the current length of the result list.
remainder_map[remainder] = len(res)
# Multiply remainder by 10 to continue division.
remainder *= 10
# Append the next digit of the quotient.
res.append(str(remainder // den))
# Update the remainder.
remainder %= den
return "".join(res)
Fraction to Recurring Decimal in Java
class Solution {
public String fractionToDecimal(int numerator, int denominator) {
// Handle the case where numerator is 0.
if (numerator == 0) {
return "0";
}
StringBuilder res = new StringBuilder();
// Determine the sign.
// If one is positive and the other is negative, the result is negative.
if ((numerator > 0) ^ (denominator > 0)) {
res.append("-");
}
// Use long to avoid overflow, especially for Integer.MIN_VALUE.
long num = Math.abs((long) numerator);
long den = Math.abs((long) denominator);
// Append the integer part.
res.append(num / den);
long remainder = num % den;
// If there is no fractional part.
if (remainder == 0) {
return res.toString();
}
// Append the decimal point.
res.append(".");
// Use a map to store remainders and their positions.
// Key: remainder, Value: index in the string builder where this remainder first occurred.
Map<Long, Integer> remainderMap = new HashMap<>();
while (remainder != 0) {
// If we have seen this remainder before, we have a repeating cycle.
if (remainderMap.containsKey(remainder)) {
// Insert the opening parenthesis at the start of the repeating part.
res.insert(remainderMap.get(remainder), "(");
// Append the closing parenthesis.
res.append(")");
break;
}
// Store the remainder and the current position.
remainderMap.put(remainder, res.length());
// Multiply remainder by 10 to continue the long division.
remainder *= 10;
// Append the next digit of the quotient.
res.append(remainder / den);
// Update the remainder.
remainder %= den;
}
return res.toString();
}
}
Fraction to Recurring Decimal in C++
class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
// Handle the case where numerator is 0.
if (numerator == 0) {
return "0";
}
string res;
// Determine the sign.
// Use XOR to check if signs are different.
if ((numerator > 0) ^ (denominator > 0)) {
res += "-";
}
// Use long long to avoid overflow when taking absolute value of INT_MIN.
long long num = abs(static_cast<long long>(numerator));
long long den = abs(static_cast<long long>(denominator));
// Append the integer part.
res += to_string(num / den);
long long rem = num % den;
// If there's no remainder, we are done.
if (rem == 0) {
return res;
}
// Append the decimal point.
res += ".";
// Use a map to store remainders and their positions.
// Key: remainder, Value: index in the string where this remainder first occurred.
unordered_map<long long, int> remainderMap;
while (rem != 0) {
// If the remainder has been seen before, we found a repeating cycle.
if (remainderMap.find(rem) != remainderMap.end()) {
// Insert '(' at the position where the cycle starts.
res.insert(remainderMap[rem], "(");
// Append ')' at the end.
res += ")";
break;
}
// Store the remainder and its current position in the result string.
remainderMap[rem] = res.length();
// Multiply remainder by 10 to continue division.
rem *= 10;
// Append the next digit of the quotient.
res += to_string(rem / den);
// Update the remainder.
rem %= den;
}
return res;
}
};
Fraction to Recurring Decimal in TypeScript
function fractionToDecimal(numerator: number, denominator: number): string {
// Handle the case where numerator is 0.
if (numerator === 0) {
return "0";
}
let res = "";
// Determine the sign.
// If one is positive and the other is negative, the result is negative.
if ((numerator > 0) !== (denominator > 0)) {
res += "-";
}
// Work with absolute values.
// JavaScript's number is a 64-bit float, which can safely handle 32-bit integers.
let num = Math.abs(numerator);
let den = Math.abs(denominator);
// Append the integer part.
res += Math.floor(num / den);
let remainder = num % den;
// If there is no fractional part.
if (remainder === 0) {
return res;
}
// Append the decimal point.
res += ".";
// Use a map to store remainders and their positions.
// Key: remainder, Value: index in the string where this remainder first occurred.
const remainderMap = new Map<number, number>();
while (remainder !== 0) {
// If we have seen this remainder before, we have a repeating cycle.
if (remainderMap.has(remainder)) {
const startIndex = remainderMap.get(remainder)!;
// Insert the opening parenthesis at the start of the repeating part.
res = res.slice(0, startIndex) + "(" + res.slice(startIndex) + ")";
break;
}
// Store the remainder and its current position.
remainderMap.set(remainder, res.length);
// Multiply remainder by 10 to continue the long division.
remainder *= 10;
// Append the next digit of the quotient.
res += Math.floor(remainder / den);
// Update the remainder.
remainder %= den;
}
return res;
}
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.