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.
Example 1:
Input: numerator = 1, denominator = 2
Output: “0.5”
Example 2:
Input: numerator = 2, denominator = 1
Output: “2”
Example 3:
Input: numerator = 2, denominator = 3
Output: “0.(6)”
给出一个分子,一个分母,返回String型的result,而且当是无限循环小数的时候,要把循环的部分用括号括起来
思路:
(1) 分子=0时返回"0",被除数不能为0,当被除数==0时,返回“0”
(2) 循环小数部分要用括号括起来,因此需要记录循环出现的位置,用HashMap
(3) 防止溢出,将除数和被除数转为long
(4) 当除数和被除数有一个是负数时,开头是负号,后面用绝对值运算
结果是String,先判断正负号,然后将整数部分加入,如果余数是0,则直接返回
如果余数>0, 加上小数点, 在HashMap中记录下余数的位置(结果String的最后)
当计算出的余数存在于HashMap中时, 证明有循环小数,这时在保存的位置处+“(",在结尾处+")"
否则将商加入结果String,计算下一步的余数,直到余数为0
//1ms..
public String fractionToDecimal(int numerator, int denominator) {
if (numerator == 0 || denominator == 0) {
return "0";
}
StringBuilder result = new StringBuilder();
if ((numerator < 0 && denominator > 0) ||
(numerator > 0 && denominator < 0)) {
result.append("-");
}
long divisor = Math.abs((long) numerator);
long divided = Math.abs((long) denominator);
long remainder = divisor % divided;
result.append(divisor / divided);
if (remainder == 0) {
return result.toString();
}
result.append(".");
HashMap<Long, Integer> pos = new HashMap<>();
while (remainder != 0) {
if (pos.containsKey(remainder)) {
result.insert(pos.get(remainder), "(");
result.append(")");
break;
} else {
pos.put(remainder, result.length());
result.append(remainder * 10 / divided);
remainder *= 10;
remainder %= divided;
}
}
return result.toString();
}