[#0166] feat(leetcode): add README, unit test and C# solution
This commit is contained in:
@@ -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
|
@@ -2,90 +2,79 @@
|
|||||||
|
|
||||||
## 題目資訊
|
## 題目資訊
|
||||||
- **難度**: Medium
|
- **難度**: Medium
|
||||||
- **標籤**:
|
- **標籤**: Hash Table, Math, Simulation
|
||||||
- **題目連結**: https://leetcode.com/problems/fraction-to-recurring-decimal/
|
- **題目連結**: https://leetcode.com/problems/fraction-to-recurring-decimal/
|
||||||
- **練習日期**: 2025-09-24
|
- **練習日期**: 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(基準/暴力):
|
1. 解法A:餘數位置哈希
|
||||||
- 思路:
|
- 思路:先處理正負號並計算整數部分;對小數部分反覆以 10 乘上餘數取商,並在 map 中紀錄餘數首次出現的索引,一旦重複即可插入括號
|
||||||
- 正確性:
|
- 正確性:每個可能的餘數介於 0 與 |denominator|-1,重複時即代表循環節開始,未重複則最後餘數為 0(有限小數)
|
||||||
- 複雜度:O(?) / O(?)
|
- 複雜度:時間 O(L) / 空間 O(L)
|
||||||
2. 解法B(優化):
|
|
||||||
- 思路:
|
|
||||||
- 正確性:
|
|
||||||
- 複雜度:O(?) / O(?)
|
|
||||||
|
|
||||||
### 乾跑(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 設計
|
## 常見陷阱
|
||||||
|
- 處理負數:符號只出現一次,判斷後用 64-bit 絕對值繼續運算避免 `--6...` 之類錯誤
|
||||||
### C# 方法簽名(示意)
|
- `INT_MIN / -1` 可能溢位:需先轉成 64-bit 再做除法與取餘數
|
||||||
```csharp
|
- 餘數 map 要記錄的是「餘數出現時的輸出索引」,找到重複時要在該位置插入 `(`
|
||||||
public class Solution {
|
- 每回合先檢查餘數是否重複再乘 10,避免多插一位或落掉循環起點
|
||||||
// TODO: 根據題意調整簽名
|
- `numerator` 為 0 時無小數部分,直接回傳 "0"
|
||||||
public int Solve(int[] nums) {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Go 方法簽名(示意)
|
|
||||||
```go
|
|
||||||
func solve(nums []int) int {
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 常見陷阱
|
|
||||||
- 邊界:空/單一/極值/全相等
|
|
||||||
- 去重:排序後跳重複、集合
|
|
||||||
- 溢位:使用 64-bit
|
|
||||||
|
|
||||||
## 測試案例
|
## 測試案例
|
||||||
|
|
||||||
### 範例輸入輸出
|
### 範例輸入輸出
|
||||||
```
|
```
|
||||||
Input: ...
|
Input: numerator = 4, denominator = 333
|
||||||
Output: ...
|
Output: "0.(012)"
|
||||||
Explanation: ...
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### 邊界清單
|
### 邊界清單
|
||||||
- [ ] 空陣列/空字串
|
- `numerator = 1, denominator = 2` → `"0.5"`(有限小數)
|
||||||
- [ ] 單一元素 / 全相同
|
- `numerator = 1, denominator = 6` → `"0.1(6)"`(循環節不從第一位開始)
|
||||||
- [ ] 含負數/0/大數
|
- `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
|
## 相關題目 / Follow-up
|
||||||
-
|
- 與任一進位制的循環小數檢測(如 base conversion)類似,可類比餘數循環檢測技巧
|
||||||
|
|
||||||
## 學習筆記
|
## 學習筆記
|
||||||
- 今天學到:
|
- 今天學到:餘數 → 索引的哈希表能精準標記循環段,搭配 `StringBuilder.Insert` 可快速加括號
|
||||||
- 卡住與修正:
|
- 卡住與修正:`int.MinValue` 轉正時會拋例外,改用 `long` 做完整流程(含乘 10 與取餘)就穩定
|
||||||
- 待優化:
|
- 另外注意:符號在輸出開頭先處理,整數和小數部分都用正數運算可避免重複符號
|
||||||
|
- 待優化:可以先行預估非循環長度以減少插入成本,但對此題影響不大
|
||||||
|
|
||||||
---
|
---
|
||||||
**總結**:這題的核心在於 ______,適合練習 ______。
|
**總結**:這題的核心在於以餘數哈希判斷循環節,適合練習小數表示與溢位處理。
|
||||||
|
|
||||||
|
@@ -5,20 +5,64 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
public class Solution {
|
public class Solution
|
||||||
// TODO: 根據題意調整簽名
|
{
|
||||||
public int Solve(int[] nums) {
|
public string FractionToDecimal(int numerator, int denominator)
|
||||||
// 實作解法
|
{
|
||||||
return 0;
|
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 class Program {
|
||||||
public static void Main() {
|
public static void Main() {
|
||||||
var s = new Solution();
|
var s = new Solution();
|
||||||
// TODO: 可加入簡單輸入/輸出測試
|
|
||||||
Console.WriteLine("Hello LeetCode 166!");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@@ -5,20 +5,23 @@ using Xunit;
|
|||||||
public class SolutionTests {
|
public class SolutionTests {
|
||||||
private readonly Solution _s = new Solution();
|
private readonly Solution _s = new Solution();
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void Example1() {
|
[InlineData(4, 333, "0.(012)")]
|
||||||
// TODO: Arrange
|
[InlineData(1, 2, "0.5")]
|
||||||
// var input = new int[] { };
|
[InlineData(1, 6, "0.1(6)")]
|
||||||
// var expected = 0;
|
[InlineData(-50, 8, "-6.25")]
|
||||||
// Act
|
[InlineData(0, 5, "0")]
|
||||||
// var got = _s.Solve(input);
|
[InlineData(1, 7, "0.(142857)")]
|
||||||
// Assert.Equal(expected, got);
|
public void FractionToDecimal_BasicAndRepeatingScenarios(int numerator, int denominator, string expected) {
|
||||||
Assert.True(true);
|
var actual = _s.FractionToDecimal(numerator, denominator);
|
||||||
|
|
||||||
|
Assert.Equal(expected, actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void EdgeCases() {
|
public void FractionToDecimal_DenominatorOne_ReturnsIntegerString() {
|
||||||
Assert.True(true);
|
var actual = _s.FractionToDecimal(2, 1);
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
Assert.Equal("2", actual);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Reference in New Issue
Block a user