public String fractionToDecimal(int numerator, int denominator) {
StringBuilder result = new StringBuilder();
String sign = (numerator < 0 == denominator < 0  numerator == 0) ? "" : "";
long num = Math.abs((long) numerator);
long den = Math.abs((long) denominator);
result.append(sign);
result.append(num / den);
long remainder = num % den;
if (remainder == 0)
return result.toString();
result.append(".");
HashMap<Long, Integer> hashMap = new HashMap<Long, Integer>();
while (!hashMap.containsKey(remainder)) {
hashMap.put(remainder, result.length());
result.append(10 * remainder / den);
remainder = 10 * remainder % den;
}
int index = hashMap.get(remainder);
result.insert(index, "(");
result.append(")");
return result.toString().replace("(0)", "");
}
Short Java solution


(numerator < 0 == denominator < 0  numerator == 0) ? "" : "", Can you explain a bit of this line. I don't quite understand the first part( numerator < 0 == denominator < 0), especially what does "==" mean. I think "==" should mean equal. So how do you decide the sign with this line. Thanks

@www2277843987 Consider the numerator is Integer.MIN_VALUE. Math.abs((long) numerator) is 2147483648, while Math.abs(numerator) is 2147483648.

said in Short Java solution:
numerator < 0 == denominator < 0  numerator == 0
This is kind of confusing at first glance and makes people who are not familiar with operator precedence feel lost. Maybe u should use
numerator < 0 ^ denominator < 0

@celestial
when
numerator and denominator have same sign or numerator is 0,
sign is +
otherwise
sign is 