69 lines
1.7 KiB
C#
69 lines
1.7 KiB
C#
// LeetCode 166: Fraction To Recurring Decimal
|
|
// 難度: Medium
|
|
// 日期: 2025-09-24
|
|
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
|
|
public class Solution
|
|
{
|
|
public string FractionToDecimal(int numerator, int denominator)
|
|
{
|
|
if (numerator == 0) return "0";
|
|
|
|
long num = numerator;
|
|
long den = denominator;
|
|
|
|
StringBuilder result = new StringBuilder();
|
|
bool isNegative = (num < 0) ^ (den < 0);
|
|
if (isNegative) result.Append('-');
|
|
|
|
num = Math.Abs(num);
|
|
den = Math.Abs(den);
|
|
|
|
long integerPart = num / den;
|
|
result.Append(integerPart);
|
|
|
|
long remainder = num % den;
|
|
if (remainder == 0) return result.ToString();
|
|
|
|
result.Append('.');
|
|
result.Append(CalculateDecimalPart(remainder, den));
|
|
|
|
return result.ToString();
|
|
}
|
|
|
|
private string CalculateDecimalPart(long remainder, long denominator)
|
|
{
|
|
StringBuilder decimalBuilder = new StringBuilder();
|
|
Dictionary<long, int> remainderMap = new Dictionary<long, int>();
|
|
|
|
while (remainder != 0)
|
|
{
|
|
if (remainderMap.TryGetValue(remainder, out int repeatIndex))
|
|
{
|
|
decimalBuilder.Insert(repeatIndex, '(');
|
|
decimalBuilder.Append(')');
|
|
break;
|
|
}
|
|
|
|
remainderMap[remainder] = decimalBuilder.Length;
|
|
remainder *= 10;
|
|
long digit = remainder / denominator;
|
|
decimalBuilder.Append(digit);
|
|
remainder %= denominator;
|
|
}
|
|
|
|
return decimalBuilder.ToString();
|
|
}
|
|
}
|
|
|
|
public class Program {
|
|
public static void Main() {
|
|
var s = new Solution();
|
|
|
|
}
|
|
}
|