Leetcode 166. Fraction to Recurring Decimal
You are given two integers representing the numerator and denominator of a fraction. Return the fraction in string format.
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)"
import java.util.HashMap;
import java.util.Map;
public class FractionToDecimal {
public String fractionToDecimal(int numerator, int denominator) {
if (numerator == 0) {
return "0";
}
StringBuilder result = new StringBuilder();
// Determine the sign.
if ((numerator > 0) ^ (denominator > 0)) {
result.append("-");
}
// Convert input values to positives for calculation
long num = Math.abs((long) numerator);
long den = Math.abs((long) denominator);
// Append the integer part
result.append(num / den);
num %= den;
if (num == 0) {
return result.toString();
}
// Append the decimal point
result.append(".");
Map<Long, Integer> map = new HashMap<>();
while (num != 0) {
if (map.containsKey(num)) {
// A repeating fraction found
result.insert(map.get(num), "(");
result.append(")");
break;
}
map.put(num, result.length());
num *= 10;
result.append(num / den);
num %= den;
}
return result.toString();
}
public static void main(String[] args) {
FractionToDecimal solution = new FractionToDecimal();
System.out.println(solution.fractionToDecimal(1, 2)); // Output: "0.5"
System.out.println(solution.fractionToDecimal(2, 1)); // Output: "2"
System.out.println(solution.fractionToDecimal(2, 3)); // Output: "0.(6)"
}
}
Map
to detect repeating remainders and construct the fractional part.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?