0%

Leetcode166-fractionToRecurringDecimal

Description

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

Example 1:

1
2
Input: numerator = 1, denominator = 2
Output: "0.5"

Example 2:
1
2
Input: numerator = 2, denominator = 1
Output: "2"

Example 3:
1
2
Input: numerator = 2, denominator = 3
Output: "0.(6)"

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public String fractionToDecimal(int numerator, int denominator) {
if (numerator == 0) return "0";
StringBuilder res = new StringBuilder();
res.append((numerator > 0) ^ (denominator > 0) ? "-" : "");
long num = Math.abs((long)numerator);
long den = Math.abs((long)denominator);

// integral part
res.append(num / den);
num %= den;
if (num == 0)
return res.toString();

// fraction part
res.append(".");
HashMap<Long, Integer> map = new HashMap<>();
map.put(num, res.length());
while(num > 0){
num *= 10;
res.append(num / den);
num %= den;
if (map.containsKey(num)){
res.insert(map.get(num), "(");
res.append(")");
break;
}
else map.put(num, res.length());
}

return res.toString();
}
}