# Java bit 96.97%

• ``````/**
* fraction to recurring decimal - 由分数转变成十进制小数
* 一定要逻辑清楚,考虑全面!!
* 分子、分母有为负, 分子为-1、分母为-2147483648等等
* 需要考虑当正常除法时, temp乘10,循环过大,int溢出的情况!!
* -2147483648/-1 = 2147483648
* -1/-2147483648 =
* <p>
* <strong>result of test:</strong><br/>
* 35 / 35 test cases passed
* Status: Accepted
* Runtime: 3 ms, bit 96.97%
*
* @param numerator   分子
* @param denominator 分母
* @return
*/
public String fractionToDecimal(int numerator, int denominator) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
StringBuffer sb = new StringBuffer();

if (numerator == 0) return "0";

//注意对整数进行绝对值取正时,一定要注意溢出的情况!!
long tempNumerator = Math.abs((long) numerator);
long tempDenominator = Math.abs((long) denominator);

int index = 0;
int mod = (int) (tempNumerator % tempDenominator);
long div = tempNumerator / tempDenominator;

if ((numerator ^ denominator) < 0) sb.append("-");
sb.append(div);
if (mod != 0) {
sb.append(".");
map.put(mod, ++index);
}

while (mod != 0) {
long temp = (long) mod * 10;
mod = (int) (temp % tempDenominator);
div = (int) (temp / tempDenominator);

sb.append(div);

Integer recur = map.get(mod);
if (recur != null) {
//循环小数
sb.insert(sb.length() - (index - recur + 1), "(");
sb.append(")");
return sb.toString();
}

map.put(mod, ++index);

}

return sb.toString();
}
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.