问题
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.
If multiple answers are possible, return any of them.
It is guaranteed that the length of the answer string is less than 104 for all the given inputs.
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)”
Example 4:
Input: numerator = 4, denominator = 333
Output: “0.(012)”
Example 5:
Input: numerator = 1, denominator = 5
Output: “0.2”
Constraints:
- − 2 31 < = n u m e r a t o r , d e n o m i n a t o r < = 2 31 − 1 -2^{31} <= numerator, denominator <= 2^{31} - 1 −231<=numerator,denominator<=231−1
- denominator != 0
方法1
时间复杂度O(n).
空间复杂度O(1).
class Solution {
public String fractionToDecimal(int numerator, int denominator) {
if(numerator == 0)
return "0";
// 用long来避免overflow
long n = Math.abs((long)numerator), d = Math.abs((long)denominator);
StringBuilder res = new StringBuilder();
Map<Long, Integer> map = new HashMap<Long, Integer>();
// 结果是否是负数
res.append((numerator > 0) == (denominator > 0) ? "" : "-");
// 整数部分
res.append(n/d);
// 去掉整数部分
n %= d;
if (n != 0){
// 小数点
res.append(".");
do {
// 分子的值和对应的位置
map.put(n, res.length());
// 乘以10之后进行除法, 得到当前位置的值
n *= 10;
res.append(n / d);
n %= d;
// 分子不为0, 并且分子没有和之前重复的时候,继续上述操作
} while (n != 0 && !map.containsKey(n));
// 如果跳出循环,但是分子不为0, 那么就是有重复
if(n != 0)
res.insert(map.get(n),"(").append(")");
}
return res.toString();
}
}