[#0166] feat(leetcode): add README, unit test and C# solution
This commit is contained in:
@@ -5,20 +5,64 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
public class Solution {
|
||||
// TODO: 根據題意調整簽名
|
||||
public int Solve(int[] nums) {
|
||||
// 實作解法
|
||||
return 0;
|
||||
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();
|
||||
// TODO: 可加入簡單輸入/輸出測試
|
||||
Console.WriteLine("Hello LeetCode 166!");
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user