[#0166] feat(leetcode): add README, unit test and C# solution

This commit is contained in:
2025-09-24 11:18:08 +08:00
parent 5189c524ef
commit 8146e2176d
4 changed files with 143 additions and 77 deletions

View File

@@ -0,0 +1,30 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.2.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "csharp", "csharp\csharp.csproj", "{CF022C7B-CAF3-706D-67E1-FB93518229B7}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestProject", "test\TestProject.csproj", "{C670389A-9CE7-B456-51E5-A79D56E199CF}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{CF022C7B-CAF3-706D-67E1-FB93518229B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CF022C7B-CAF3-706D-67E1-FB93518229B7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CF022C7B-CAF3-706D-67E1-FB93518229B7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CF022C7B-CAF3-706D-67E1-FB93518229B7}.Release|Any CPU.Build.0 = Release|Any CPU
{C670389A-9CE7-B456-51E5-A79D56E199CF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C670389A-9CE7-B456-51E5-A79D56E199CF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C670389A-9CE7-B456-51E5-A79D56E199CF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C670389A-9CE7-B456-51E5-A79D56E199CF}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {C5790EDA-C36F-4FC3-877D-C7E20837E160}
EndGlobalSection
EndGlobal

View File

@@ -2,90 +2,79 @@
## 題目資訊
- **難度**: Medium
- **標籤**:
- **標籤**: Hash Table, Math, Simulation
- **題目連結**: https://leetcode.com/problems/fraction-to-recurring-decimal/
- **練習日期**: 2025-09-24
- **目標複雜度**: 時間 O(?)、空間 O(?)
- **目標複雜度**: 時間 O(L)、空間 O(L)L 為輸出字串長度,最多 10^4
## 題目描述
> 在這裡貼上題目的完整描述(或重點)
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.
If multiple answers are possible, return **any of them**.
It is **guaranteed** that the length of the answer string is less than `10^4` for all the given inputs.
## 先備條件與限制
- 輸入限制:n ∈ [?, ?]、值域 ∈ [?, ?]
- 回傳/輸出格式:...
- 其他:是否允許排序/就地修改
- 輸入限制:`-2^31 <= numerator, denominator <= 2^31 - 1`,且 denominator ≠ 0
- 回傳/輸出格式:回傳十進位字串;有限小數直接輸出,小數有循環時用括號標記循環段
- 其他:允許使用 64-bit 以避免在取絕對值時溢位
## 解題思路
### 初步分析
- 類型:雙指針 / 滑動視窗 / 排序 / DP / 貪心 / 圖論 ...
- 關鍵觀察:
- 複雜度目標理由:
- 類型:數學 / 模擬 / 哈希
- 關鍵觀察:整數除法僅靠餘數決定下一個小數位;相同餘數必定導致循環,位置可透過哈希表還原
- 複雜度目標理由:每個餘數最多處理一次,因此時間與空間成正比於輸出長度 L
### 解法比較
1. 解法A(基準/暴力):
- 思路:
- 正確性:
- 複雜度O(?) / O(?)
2. 解法B優化
- 思路:
- 正確性:
- 複雜度O(?) / O(?)
1. 解法A:餘數位置哈希
- 思路:先處理正負號並計算整數部分;對小數部分反覆以 10 乘上餘數取商,並在 map 中紀錄餘數首次出現的索引,一旦重複即可插入括號
- 正確性:每個可能的餘數介於 0 與 |denominator|-1重複時即代表循環節開始未重複則最後餘數為 0有限小數
- 複雜度:時間 O(L) / 空間 O(L)
### 乾跑Dry Run
- 範例:...
## 實作細節
- 先處理 `numerator == 0` 直接回傳 "0"
- 判斷結果正負號,使用 `long`/`long long` 取絕對值避免 `INT_MIN` 無法轉正的問題
- `integer_part = abs_num / abs_den` 直接加入結果,小數部分以餘數 `remainder = abs_num % abs_den` 開始
- 使用字典 `remainder -> index` 紀錄餘數在結果字串中的位置;迴圈內:餘數乘 10取下一位商並更新餘數
- 若餘數為 0表示小數結束不需括號若餘數再度出現在對應索引插入 `(`,在結尾加 `)`
## 實作細節與 API 設計
### C# 方法簽名(示意)
```csharp
public class Solution {
// TODO: 根據題意調整簽名
public int Solve(int[] nums) {
return 0;
}
}
```
### Go 方法簽名(示意)
```go
func solve(nums []int) int {
return 0
}
```
### 常見陷阱
- 邊界:空/單一/極值/全相等
- 去重:排序後跳重複、集合
- 溢位:使用 64-bit
## 常見陷阱
- 處理負數:符號只出現一次,判斷後用 64-bit 絕對值繼續運算避免 `--6...` 之類錯誤
- `INT_MIN / -1` 可能溢位:需先轉成 64-bit 再做除法與取餘數
- 餘數 map 要記錄的是「餘數出現時的輸出索引」,找到重複時要在該位置插入 `(`
- 每回合先檢查餘數是否重複再乘 10避免多插一位或落掉循環起點
- `numerator` 為 0 時無小數部分,直接回傳 "0"
## 測試案例
### 範例輸入輸出
```
Input: ...
Output: ...
Explanation: ...
Input: numerator = 4, denominator = 333
Output: "0.(012)"
```
### 邊界清單
- [ ] 空陣列/空字串
- [ ] 單一元素 / 全相同
- [ ] 含負數/0/大數
- [ ] 去重
- [ ] 大資料壓力
- `numerator = 1, denominator = 2``"0.5"`(有限小數)
- `numerator = 1, denominator = 6``"0.1(6)"`(循環節不從第一位開始)
- `numerator = -50, denominator = 8``"-6.25"`(負數與有限小數)
- `numerator = 0, denominator = 5``"0"`(整數結果)
- `numerator = 1, denominator = 7``"0.(142857)"`(較長的循環節)
## 複雜度分析
- 最壞:時間 O(?)、空間 O(?)
- 最壞:時間 O(L)、空間 O(L)
- L 為輸出字串長度,等同於需要處理的餘數數量上限(題目保證 < 10^4
## 相關題目 / Follow-up
-
- 與任一進位制的循環小數檢測 base conversion類似可類比餘數循環檢測技巧
## 學習筆記
- 今天學到
- 卡住與修正
- 待優化:
- 今天學到餘數 索引的哈希表能精準標記循環段搭配 `StringBuilder.Insert` 可快速加括號
- 卡住與修正`int.MinValue` 轉正時會拋例外改用 `long` 做完整流程含乘 10 與取餘就穩定
- 另外注意符號在輸出開頭先處理整數和小數部分都用正數運算可避免重複符號
- 待優化可以先行預估非循環長度以減少插入成本但對此題影響不大
---
**總結**這題的核心在於 ______,適合練習 ______
**總結**這題的核心在於以餘數哈希判斷循環節適合練習小數表示與溢位處理

View File

@@ -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!");
}
}

View File

@@ -5,20 +5,23 @@ using Xunit;
public class SolutionTests {
private readonly Solution _s = new Solution();
[Fact]
public void Example1() {
// TODO: Arrange
// var input = new int[] { };
// var expected = 0;
// Act
// var got = _s.Solve(input);
// Assert.Equal(expected, got);
Assert.True(true);
[Theory]
[InlineData(4, 333, "0.(012)")]
[InlineData(1, 2, "0.5")]
[InlineData(1, 6, "0.1(6)")]
[InlineData(-50, 8, "-6.25")]
[InlineData(0, 5, "0")]
[InlineData(1, 7, "0.(142857)")]
public void FractionToDecimal_BasicAndRepeatingScenarios(int numerator, int denominator, string expected) {
var actual = _s.FractionToDecimal(numerator, denominator);
Assert.Equal(expected, actual);
}
[Fact]
public void EdgeCases() {
Assert.True(true);
public void FractionToDecimal_DenominatorOne_ReturnsIntegerString() {
var actual = _s.FractionToDecimal(2, 1);
Assert.Equal("2", actual);
}
}