-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
36 lines (34 loc) · 939 Bytes
/
Solution.cs
File metadata and controls
36 lines (34 loc) · 939 Bytes
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
public class Solution
{
public string FractionToDecimal(int numerator, int denominator)
{
Dictionary<long, int> calc = [];
StringBuilder ans = new();
StringBuilder decimalDigit = new();
long num = numerator;
long den = denominator;
if (num * den < 0) ans.Append('-');
num = Math.Abs(num);
den = Math.Abs(den);
ans.Append(num / den);
num %= den;
if (num == 0) return ans.ToString();
ans.Append('.');
int pos = 0;
while (num > 0)
{
if (calc.ContainsKey(num)) break;
calc[num] = pos++;
num *= 10;
decimalDigit.Append(num / den);
num %= den;
}
if (num != 0)
{
decimalDigit.Insert(calc[num], '(');
decimalDigit.Append(')');
}
ans.Append(decimalDigit);
return ans.ToString();
}
}