Fraction to Recurring Decimal
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.
For example,
Given numerator = 1, denominator = 2, return "0.5". Given numerator = 2, denominator = 1, return "2". Given numerator = 2, denominator = 3, return "0.(6)".
Credits:Special thanks to @Shangrila for adding this problem and creating all test cases.
Solution
public class Solution {
public String fractionToDecimal(int numerator1, int denominator1) {
Long denominator = new Long(denominator1);
Long numerator = new Long(numerator1);
if (denominator == 0) return "";
if (numerator == 0) return "0";
boolean falg =true;
if (numerator < 0 && denominator > 0) falg = false;
if (numerator > 0 && denominator < 0) falg = false;
denominator = Math.abs(denominator);
numerator = Math.abs(numerator);
StringBuffer sb = new StringBuffer();
Long d = numerator / denominator;
sb.append(d);
Long r = (numerator % denominator);
if (r == 0) {
if (!falg) {
sb.insert(0, "-");
}
return sb.toString();
}
sb.append(".");
r *= 10;
Map<Long, Integer> map = new HashMap<>();
while (r != 0) {
if (map.containsKey(r)) {
sb.insert(map.get(r), "(");
sb.append(")");
break;
}
map.put(r, sb.length());
sb.append(r / denominator);
r = r % denominator;
r *= 10;
}
if (!falg) {
sb.insert(0, "-");
}
return sb.toString();
}
}