Prompt file imported from HyperLee/BitManipulation (
.github/prompts/BitManipulation.prompt.md). Copyright stays with the author.
BitManipulation 開發規格書(Single Source of Truth)
本文件為 BitManipulation 專案唯一事實來源(Single Source of Truth, SSoT)。 所有實作、測試、文件撰寫均須以此規格為準;如需變更,請先修訂本文件再行實作。
1. 專案概述(Overview)
1.1 專案目的(Purpose)
建構一個以 C# / .NET 10 為基礎、聚焦於 位元運算(Bit Manipulation) 的學習與實戰專案,內容涵蓋:
- 六大核心位元運算子(Bitwise Operators)的觀念、API 與互動式示範。
- 常見實戰技巧(Bit Tricks):奇偶判斷、2 的冪次、變數交換、漢明重量(Hamming Weight)、位元遮罩(Bit Mask)等。
- 進階位元演算法(Advanced Algorithms):Single Number、Subsets、Gray Code、Bit Compression 等。
- 15 題精選 LeetCode 位元運算題庫,含完整解題思路與複雜度分析。
- 完整 xUnit 單元測試與教學文件。
1.2 學習目標(Learning Objectives)
完成本專案後,讀者 / 開發者應能夠:
- 熟練使用 C# 中的位元運算子(
&、|、^、~、<<、>>、>>>)。 - 推導並實作常見位元技巧背後的數學原理(補數、二補數、位元遮罩)。
- 在演算法題目中辨識可用位元運算優化的場景。
- 撰寫具邊界條件、覆蓋率 ≥ 90% 的 xUnit 單元測試。
- 善用
System.Numerics.BitOperations等內建高效 API。
1.3 預期產出(Deliverables)
| 類別 | 產出 |
|---|---|
| 程式碼 | BitManipulation(Console + 類別庫)、BitManipulation.Tests(xUnit) |
| 文件 | docs/01-fundamentals.md ~ docs/05-leetcode.md、README.md |
| 測試 | 全 xUnit 測試綠燈,覆蓋率 ≥ 90% |
| 建置 | dotnet build 通過且 0 警告 |
1.4 適用對象與先備知識(Audience & Prerequisites)
- 主要讀者:本專案開發者、GitHub Copilot Agent。
- 次要讀者:研讀位元運算與演算法的 C# / .NET 學習者。
- 先備知識:C# 基本語法、.NET CLI 操作、基礎資料結構與演算法。
2. 技術棧與環境(Tech Stack)
| 項目 | 版本 / 工具 | 說明 |
|---|---|---|
| Language | C# 14 | 採用最新語言特性(primary constructor、collection expression 等) |
| Runtime | .NET 10 | <TargetFramework>net10.0</TargetFramework> |
| 測試框架 | xUnit(最新穩定版) | 搭配 Microsoft.NET.Test.Sdk |
| 斷言函式庫 | xUnit 內建 Assert |
不引入第三方 fluent assertion |
| 效能量測(選用) | BenchmarkDotNet | 僅在 §12 效能對照範例使用 |
| 編輯器 | VS Code / Visual Studio / Rider | 共用 .editorconfig |
| 版本控制 | Git | .gitignore 採用 .NET 標準範本 |
啟用設定(所有 .csproj 共通):
<Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings><LangVersion>latest</LangVersion><TreatWarningsAsErrors>true</TreatWarningsAsErrors>(驗收條件之一)
3. 解決方案結構(Solution Layout)
BitManipulation.sln
├── BitManipulation/ # 主專案(Console + 類別庫)
│ ├── BitManipulation.csproj
│ ├── Program.cs # Console 進入點 + 主選單
│ ├── Core/
│ │ └── BitwiseOperators.cs # 六大運算子 API 與示範
│ ├── Algorithms/
│ │ ├── BitTricks.cs # 實戰技巧
│ │ └── AdvancedBitAlgorithms.cs # 進階演算法
│ ├── LeetCode/
│ │ ├── Solution0136.cs # Single Number
│ │ ├── Solution0137.cs # Single Number II
│ │ ├── Solution0260.cs # Single Number III
│ │ ├── Solution0191.cs # Number of 1 Bits
│ │ ├── Solution0231.cs # Power of Two
│ │ ├── Solution0338.cs # Counting Bits
│ │ ├── Solution0389.cs # Find the Difference
│ │ ├── Solution0371.cs # Sum of Two Integers
│ │ ├── Solution0461.cs # Hamming Distance
│ │ ├── Solution0477.cs # Total Hamming Distance
│ │ ├── Solution0201.cs # Bitwise AND of Numbers Range
│ │ ├── Solution0693.cs # Binary Number with Alternating Bits
│ │ ├── Solution0762.cs # Prime Number of Set Bits
│ │ ├── Solution1009.cs # Complement of Base 10 Integer
│ │ └── Solution0078.cs # Subsets
│ └── UI/
│ ├── MenuRunner.cs # 主選單分派
│ └── ConsoleHelper.cs # 輸入驗證 / 顯示工具
│
├── BitManipulation.Tests/ # xUnit 測試專案
│ ├── BitManipulation.Tests.csproj
│ ├── Core/
│ │ └── BitwiseOperatorsTests.cs
│ ├── Algorithms/
│ │ ├── BitTricksTests.cs
│ │ └── AdvancedBitAlgorithmsTests.cs
│ └── LeetCode/
│ └── Solution{XXXX}Tests.cs # 對應每題
│
├── docs/ # 教學文件
│ ├── 01-fundamentals.md
│ ├── 02-operators.md
│ ├── 03-tricks.md
│ ├── 04-advanced.md
│ └── 05-leetcode.md
│
├── README.md
├── .editorconfig
└── .github/
├── instructions/csharp.instructions.md
└── prompts/BitManipulation.prompt.md # 本規格書
3.1 命名空間(Namespaces)
| 命名空間 | 內容 |
|---|---|
BitManipulation |
Program、UI |
BitManipulation.Core |
BitwiseOperators |
BitManipulation.Algorithms |
BitTricks、AdvancedBitAlgorithms |
BitManipulation.LeetCode |
Solution{XXXX} |
BitManipulation.UI |
MenuRunner、ConsoleHelper |
BitManipulation.Tests.* |
對應測試命名空間 |
4. 功能模組規格(Functional Modules)
API 共通要求:所有公開方法須附 XML doc,含
<summary>、<param>、<returns>、<example>;所有靜態類別之公開 API 標示為public static。
4.1 核心運算子示範(BitManipulation.Core.BitwiseOperators)
| 方法 | 簽章 | 說明 |
|---|---|---|
| AND | static int And(int a, int b) |
a & b,按位元 AND |
| OR | static int Or(int a, int b) |
a | b,按位元 OR |
| XOR | static int Xor(int a, int b) |
a ^ b,按位元 XOR |
| NOT | static int Not(int a) |
~a,按位元取反(一補數) |
| LeftShift | static int LeftShift(int a, int n) |
a << n |
| ArithmeticRightShift | static int ArithmeticRightShift(int a, int n) |
a >> n,保留符號 |
| LogicalRightShift | static int LogicalRightShift(int a, int n) |
a >>> n(C# 11+),不保留符號 |
| ToBinaryString | static string ToBinaryString(int a, int width = 32) |
將整數轉為定寬二進位字串,方便 Console 展示 |
- 輸入限制:位移量
n必須為0 ≤ n < 32,超出範圍丟ArgumentOutOfRangeException。 - 複雜度:所有方法 O(1)。
4.2 實戰技巧(BitManipulation.Algorithms.BitTricks)
| 方法 | 簽章 | 說明與公式 |
|---|---|---|
| 奇偶判斷 | static bool IsOdd(int n) |
(n & 1) == 1 |
| 2 的冪次 | static bool IsPowerOfTwo(int n) |
n > 0 && (n & (n - 1)) == 0 |
| XOR 交換 | static (int a, int b) Swap(int a, int b) |
透過 XOR 交換變數,回傳 tuple |
| 漢明重量 | static int HammingWeight(uint n) |
計算二進位中 1 的個數(Brian Kernighan 演算法) |
| 設定位元 | static int SetBit(int value, int index) |
value | (1 << index) |
| 清除位元 | static int ClearBit(int value, int index) |
value & ~(1 << index) |
| 切換位元 | static int ToggleBit(int value, int index) |
value ^ (1 << index) |
| 取得位元 | static bool GetBit(int value, int index) |
((value >> index) & 1) == 1 |
| 取最低位 1 | static int LowestSetBit(int n) |
n & -n |
| 清除最低位 1 | static int ClearLowestSetBit(int n) |
n & (n - 1) |
- 邊界條件:
index必須0 ≤ index < 32,違反者拋ArgumentOutOfRangeException。 - 複雜度:除
HammingWeight為 O(k)(k 為 1 的個數)外,其餘 O(1)。
4.3 進階演算法(BitManipulation.Algorithms.AdvancedBitAlgorithms)
| 方法 | 簽章 | 說明 |
|---|---|---|
| Single Number I | static int SingleNumber(int[] nums) |
全 XOR 找出唯一只出現一次的數 |
| Single Number II | static int SingleNumberII(int[] nums) |
每位元 mod 3 的位元計數法 |
| Single Number III | static int[] SingleNumberIII(int[] nums) |
兩唯一數,利用 XOR 與最低位 1 分組 |
| Subsets(位元枚舉) | static IList<IList<int>> Subsets(int[] nums) |
用 1 << n 枚舉所有子集 |
| Gray Code | static IList<int> GrayCode(int n) |
i ^ (i >> 1) 產生 n 位元格雷碼 |
| Bit Compression | static long Compress(IEnumerable<bool> bits) |
將布林序列壓縮為 long(最多 64 位元) |
- 邊界條件:
Subsets限制nums.Length ≤ 20;Compress超過 64 位元拋例外。 - 複雜度:詳見
docs/04-advanced.md。
4.4 LeetCode 題集(BitManipulation.LeetCode.Solution{XXXX})
每個題目對應一個 Solution{XXXX} 類別,至少包含:
/// <summary>
/// LeetCode {XXXX}. {Title}
/// 連結:https://leetcode.com/problems/{slug}/
/// 難度:{Easy|Medium|Hard}
/// 標籤:Bit Manipulation, ...
/// 思路:{簡述}
/// 時間複雜度:O(?)
/// 空間複雜度:O(?)
/// </summary>
public sealed class Solution{XXXX}
{
public {ReturnType} {MethodName}({Params}) { ... }
}
各題公開方法須與 LeetCode 題目原始簽章一致(命名與型別),方便對照。
5. LeetCode 精選題目清單(15 題)
| # | 題號 | 難度 | 標籤 | 對應檔案 | 核心技巧 |
|---|---|---|---|---|---|
| 1 | 136 | Easy | Array, Bit Manipulation | Solution0136.cs |
全 XOR |
| 2 | 137 | Medium | Bit Manipulation | Solution0137.cs |
位元計數 mod 3 |
| 3 | 260 | Medium | Bit Manipulation | Solution0260.cs |
XOR + 最低位 1 分組 |
| 4 | 191 | Easy | Bit Manipulation | Solution0191.cs |
Brian Kernighan |
| 5 | 231 | Easy | Bit Manipulation | Solution0231.cs |
n & (n-1) == 0 |
| 6 | 338 | Easy | Dynamic Programming, Bit Manipulation | Solution0338.cs |
DP:dp[i] = dp[i>>1] + (i & 1) |
| 7 | 389 | Easy | Hash Table, Bit Manipulation, String | Solution0389.cs |
XOR 累加字元 |
| 8 | 371 | Medium | Math, Bit Manipulation | Solution0371.cs |
XOR + 進位(不使用 +) |
| 9 | 461 | Easy | Bit Manipulation | Solution0461.cs |
HammingWeight(x ^ y) |
| 10 | 477 | Medium | Bit Manipulation, Math | Solution0477.cs |
對每位元計數貢獻 |
| 11 | 201 | Medium | Bit Manipulation | Solution0201.cs |
共同前綴(不斷右移) |
| 12 | 693 | Easy | Bit Manipulation | Solution0693.cs |
(n ^ (n>>1)) + 1 為 2 的冪 |
| 13 | 762 | Easy | Math, Bit Manipulation | Solution0762.cs |
計數 + 質數判定 |
| 14 | 1009 | Easy | Bit Manipulation | Solution1009.cs |
取得最高位後建構遮罩 |
| 15 | 78 | Medium | Array, Backtracking, Bit Manipulation | Solution0078.cs |
子集位元枚舉 |
每題在
docs/05-leetcode.md中皆有專屬段落,包含題意翻譯、範例、解法推導、複雜度與常見陷阱。
6. Console UI 規格
6.1 主選單(Main Menu)
============================================
BitManipulation 位元運算示範
============================================
[1] 核心運算子(Bitwise Operators)
[2] 實戰技巧(Bit Tricks)
[3] 進階演算法(Advanced Algorithms)
[4] LeetCode 題集
[0] 離開
--------------------------------------------
請選擇:
6.2 子選單規範
- 每個分類進入後顯示功能列表(編號 + 名稱)。
- 使用者輸入編號 → 提示輸入參數 → 顯示結果與二進位視覺化(呼叫
BitwiseOperators.ToBinaryString)→ 等待Enter返回。
6.3 輸入驗證
| 情境 | 行為 |
|---|---|
| 非數字輸入 | 顯示「請輸入有效整數」並重新提示 |
| 數值溢位 | 顯示「超出 Int32 範圍」並重新提示 |
| 位移量 < 0 或 ≥ 32 | 顯示「位移量需介於 0–31」並重新提示 |
| 主選單輸入未列出的編號 | 顯示「無此選項」並重新顯示主選單 |
任意位置輸入 q、Q、exit |
退回上一層或結束程式 |
6.4 退出機制
- 主選單輸入
0→ 顯示「Goodbye」→ 結束程式(return 0)。 - 任何未捕獲例外應由
Program.Main最外層 try/catch 攔截,輸出友善訊息並回傳非零狀態碼。
7. 編碼規範(Coding Standards)
本節為
.github/instructions/csharp.instructions.md的補充與專案級強制要求。
- 語言版本:C# 14、
<LangVersion>latest</LangVersion>。 - 命名空間:一律使用 file-scoped namespace。
- 命名:型別 / 公開成員 PascalCase;私有欄位 / 區域變數 camelCase;介面以
I起始。 - null 檢查:使用
is null/is not null。 - Nullable:全專案啟用,公開 API 不接受
null時應於進入點檢查並拋ArgumentNullException。 - 使用宣告:優先
usingdeclaration(C# 8+)。 - 模式比對:迴圈、條件分支盡量採用 switch expression / pattern matching。
nameof:傳遞成員名稱字串(如例外訊息、ArgumentOutOfRangeException)一律使用nameof。- XML 文件:所有
public與protected成員均須提供 XML doc;位元運算類別額外提供<example>與<code>。 - 避免裝箱:位元運算路徑禁止對
int、long、uint等型別進行不必要裝箱(不要將其透過object、非泛型集合存取)。 - 禁用:
goto、未經設計的unsafe。
8. 測試規範(Testing)
8.1 框架與套件
- 測試框架:xUnit(
xunit、xunit.runner.visualstudio)。 - 涵蓋率工具:
coverlet.collector(透過dotnet test --collect:"XPlat Code Coverage")。 - 不引入第三方 mocking / fluent assertion 框架。
8.2 命名與結構
- 測試類別:
{被測類別名稱}Tests。 - 測試方法:
Method_Scenario_Expected,例如IsPowerOfTwo_WhenInputIsZero_ReturnsFalse。 - 不撰寫
Arrange / Act / Assert註解。 - 優先使用
[Theory]+[InlineData],相同邏輯共用單一測試方法。
8.3 案例覆蓋要求
每個公開方法至少 3 種案例:
- 正常案例(Happy path)
- 邊界案例:0、1、
int.MinValue、int.MaxValue、空陣列、單一元素等 - 極端 / 例外案例:負位移、超出範圍、
null輸入等(驗證例外型別)
8.4 覆蓋率目標
- 行覆蓋率(line coverage)≥ 90%。
- 分支覆蓋率(branch coverage)≥ 85%。
- 由 CI 或
dotnet test報告檢查;未達標視為驗收失敗。
8.5 範例(僅作格式示意,非實作)
public class BitTricksTests
{
[Theory]
[InlineData(1, true)]
[InlineData(2, false)]
[InlineData(0, false)]
[InlineData(int.MaxValue, true)]
public void IsOdd_VariousInputs_ReturnsExpected(int input, bool expected)
=> Assert.Equal(expected, BitTricks.IsOdd(input));
}
9. 教學文件規格(docs/)
每篇 Markdown 須包含以下固定段落:
- 學習目標(Learning Objectives)
- 理論背景(Theory)
- C# 範例(Examples):可執行片段,引用本專案 API。
- 複雜度分析(Complexity)
- 常見陷阱(Pitfalls)
- 延伸閱讀(Further Reading)
| 檔案 | 主題 |
|---|---|
docs/01-fundamentals.md |
基礎理論:二進位、十六進位、原碼 / 反碼 / 二補數、有號 vs 無號 |
docs/02-operators.md |
六大運算子:AND / OR / XOR / NOT / << / >> / >>> 真值表、視覺圖解 |
docs/03-tricks.md |
實戰技巧推導:奇偶、2 的冪、Swap、Hamming Weight、Bit Mask |
docs/04-advanced.md |
進階:Single Number 系列、Subsets 枚舉、Gray Code、Bit Compression |
docs/05-leetcode.md |
15 題分類、解題模板、範例、複雜度對照表 |
10. README.md 規格
README.md 須涵蓋:
- 專案簡介:一段話說明定位與目標。
- 特色(Features):條列 4–6 點。
- 快速開始(Quick Start):
git clone <repo> cd BitManipulation dotnet build dotnet run --project BitManipulation dotnet test - 目錄結構:與 §3 一致的樹狀圖。
- 執行方式:Console 互動範例截圖或 ASCII 範例。
- 學習路徑(Learning Path):建議順序
docs/01 → 05。 - 貢獻指南(Contributing):分支策略、commit 規範、PR 檢查清單。
- 授權(License):MIT。
- 參考資料:與 §15 對齊。
11. 錯誤處理與邊界條件(Error Handling & Edge Cases)
| 情境 | 處理策略 |
|---|---|
| 位移量為負或 ≥ 位元寬度 | 拋 ArgumentOutOfRangeException(nameof(n)) |
int.MinValue 取絕對值 |
演算法須使用 uint / long,避免 Math.Abs(int.MinValue) 溢位 |
IsPowerOfTwo(0) / 負數 |
回傳 false,明示於 XML doc |
HammingWeight 接受 uint |
不接受 int,避免符號擴充歧義 |
LeetCode Add(a,b)(371 題) |
使用 unchecked 區塊,允許 32 位元溢位 |
| 空陣列輸入 | Single Number 系列需文件中明示為 undefined / 拋 ArgumentException |
null 陣列 / 字串 |
一律拋 ArgumentNullException |
| Console 輸入無效 | 不丟例外,僅重新提示 |
12. 效能考量(Performance Considerations,非強制)
- 對於漢明重量、
TrailingZeroCount、LeadingZeroCount等場景,優先使用System.Numerics.BitOperations,因其在支援的 CPU 上會編譯為POPCNT/LZCNT/TZCNT指令。 - 在熱路徑(hot path)避免:
- 對
int、uint進行不必要裝箱(如塞入ArrayList、object[])。 - 使用 LINQ 取代簡單迴圈(除非可讀性顯著提升)。
- 對
- 若加入 BenchmarkDotNet:
- 放置於獨立
BitManipulation.Benchmarks專案(選用)。 - 不影響主專案 / 測試專案建置。
- 放置於獨立
13. 里程碑(Milestones)
| 代號 | 範圍 | 完成定義(Definition of Done) |
|---|---|---|
| M1 | §4.1 核心運算子 + 對應測試 | BitwiseOperators API 完成、測試綠燈、覆蓋率達標 |
| M2 | §4.2 實戰技巧 + 測試 | BitTricks API 完成、邊界例外驗證 |
| M3 | §4.3 進階演算法 + 測試 | AdvancedBitAlgorithms API 完成 |
| M4 | §4.4 / §5 LeetCode 15 題 + 測試 | 每題至少 3 案例(含官方範例) |
| M5 | §9 教學文件 docs/01-05 |
6 段落齊全、範例可執行 |
| M6 | README、收尾、CI 驗收 | §14 全項通過 |
14. 驗收標準(Acceptance Criteria)
專案視為「完成」須同時滿足:
-
dotnet build -c Release0 警告 0 錯誤(已啟用TreatWarningsAsErrors)。 -
dotnet test全綠燈。 - 行覆蓋率 ≥ 90%、分支覆蓋率 ≥ 85%。
- 所有
publicAPI 皆具備 XML doc,且具範例之核心 API 含<example>。 - §3 解決方案結構與檔案命名完全一致。
- §5 列出之 15 題皆已實作並通過 LeetCode 官方範例對應的測試案例。
-
docs/01-05與README.md全部存在,無 TODO / 佔位符。 - Console 主選單可成功執行所有功能而不拋未捕獲例外。
- 規格書(本檔)與實作一致,若有差異須先修正本檔。
15. 參考資料(References)
- Wikipedia — Bitwise operation:https://en.wikipedia.org/wiki/Bitwise_operation
- Wikipedia — Two's complement:https://en.wikipedia.org/wiki/Two%27s_complement
- Wikipedia — Gray code:https://en.wikipedia.org/wiki/Gray_code
- GeeksforGeeks — Bit Manipulation:https://www.geeksforgeeks.org/bit-manipulation/
- Henry S. Warren, Jr. — Hacker's Delight (2nd Edition)
- LeetCode — Bit Manipulation tag:https://leetcode.com/tag/bit-manipulation/
- Microsoft Docs —
System.Numerics.BitOperations:https://learn.microsoft.com/dotnet/api/system.numerics.bitoperations - Microsoft Docs — Bitwise and shift operators:https://learn.microsoft.com/dotnet/csharp/language-reference/operators/bitwise-and-shift-operators
規格書變更紀錄(Changelog)
- v1.0:依
撰寫計畫§1–§15 章節大綱完整建立規格書,移除原檔 OCR 雜訊與斷句錯誤。