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)".
- 首先判断符号,使用Math.signum()。如果是正数,返回1;负数,返回-1;是0,返回0。
- 考虑到溢出,辅助变量定义成long。这是因为如果:那么在numerator * 10 后,就溢出了。
- 要取绝对值,因为 -2 % 3 = -2, -2 % -3 = -2
- 分析57,余数分别是 5 1 3 2 6 4 5,到5处就出现了循环。因为余数必然在[0,7)范围内,如果不能除尽,必然是无限循环小数。循环的位置,就是某余数第一次出现的位置,至当前该余数出现的位置(该余数是所有余数中,第一个出现2次的)。
public String fractionToDecimal(int numerator, int denominator) {
String sign = "";
if (Math.signum(numerator) * Math.signum(denominator) < 0) {
sign = "-";
}
long n = Math.abs(numerator);
long d = Math.abs(denominator);
String intPart = Math.abs(n / d) "";
// 如果整除,直接返回结果
if (n % d == 0) {
return sign intPart;
}
// 计算小数部分
n %= d;
n *= 10;
StringBuilder sb = new StringBuilder();
Map<Long, Integer> mod = new HashMap<Long, Integer>();
for (int i = 0; n != 0; i ) {
long q = n / d;
Integer start = mod.get(n / 10);
if (start != null) {
sb.insert(start, "(");
sb.append(")");
break;
}
sb.append(Math.abs(q));
mod.put(n / 10, i);
n %= d;
n *= 10;
}
String fractionalPart = sb.toString();
return sign intPart "." fractionalPart;
}