forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cs
57 lines (54 loc) · 1.29 KB
/
Solution.cs
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// https://leetcode.com/problems/fraction-to-recurring-decimal/
using System.Collections.Generic;
using System.Text;
public partial class Solution
{
public string FractionToDecimal(int numerator, int denominator)
{
var n = (long)numerator;
var d = (long)denominator;
var sb = new StringBuilder();
if (n < 0)
{
n = -n;
if (d < 0)
{
d = -d;
}
else
{
sb.Append('-');
}
}
else if (n > 0 && d < 0)
{
d = -d;
sb.Append('-');
}
sb.Append(n / d);
n = n % d;
if (n != 0)
{
sb.Append('.');
var dict = new Dictionary<long, int>();
while (n != 0)
{
int index;
if (dict.TryGetValue(n, out index))
{
sb.Insert(index, '(');
sb.Append(')');
break;
}
else
{
dict.Add(n, sb.Length);
n *= 10;
sb.Append(n / d);
n %= d;
}
}
}
return sb.ToString();
}
}