leetcode
package com.leetCode;
import java.util.HashMap;
import java.util.Map;
/*
problem :Fraction to Recurring Decimal
descript:
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)".
*/
public class FractiontoRecurringDecimal {
public static String fractionToDecimal(int numerator, int denominator) {
Map<Long, Integer> map = new HashMap<Long, Integer>();
if (0 == numerator)
return "0";
if (0 == denominator)
return "";
StringBuilder builder = new StringBuilder();
if (((numerator < 0) ^ (denominator < 0))) {
builder.append("-");
}
// conver to long
long b = numerator;
long a = denominator;
b = Math.abs(b);
a = Math.abs(a);
long ans = b / a;
builder.append(String.valueOf(ans));
long c = (b % a) * 10;
if (0 == c)
return builder.toString();
builder.append(".");
while (c != 0) {
if (map.containsKey(c)) {
int beg = map.get(c);
String result = "";
result += builder.substring(0, beg);
result += "(" + builder.substring(beg) + ")";
return result;
}
map.put(c, builder.length());
builder.append(c / a);
c = (c % a) * 10;
}
return builder.toString();
}
}