การแปลงฐานสิบเป็นฐานสอง (Decimal to Binary) ด้วย Recursion เป็นตัวอย่างคลาสสิกของการใช้ Recursive Algorithm
หลักการ Recursive
Binary Representation = (n % 2) + 10 * Binary(n / 2)
- Base Case: n == 0 → return 0
- Recursive Case: คำนวณ bit ล่างสุด (n % 2) แล้ว Shift เหลือ (n / 2)
ตัวอย่างโค้ด (แก้ไขจากต้นฉบับที่มี Bug)
using System;
public class Program
{
public static void Main()
{
int dec = 30;
Console.Write($"Decimal = {dec}");
Console.Write($"\nBinary of {dec} = ");
DisplayBinary(dec);
Console.WriteLine();
}
// แก้ไข: คืนค่า string แทนการ Print ในฟังก์ชัน
public static string DisplayBinary(int dec)
{
if (dec == 0) return "0";
if (dec == 1) return "1";
return DisplayBinary(dec / 2) + (dec % 2).ToString();
}
}
ผลลัพธ์
Decimal = 30
Binary of 30 = 11110
วิธี Built-in (แนะนำสำหรับ Production)
int dec = 30;
string binary = Convert.ToString(dec, 2); // "11110"
// หรือ
string binary = Convert.ToString(dec, 2).PadLeft(8, '0'); // "00011110" (8-bit)
Iterative Version (ไม่ใช้ Recursion - ปลอดภัยกว่า Stack Overflow)
public static string ToBinaryIterative(int n)
{
if (n == 0) return "0";
var bits = new System.Text.StringBuilder();
while (n > 0)
{
bits.Insert(0, n % 2);
n /= 2;
}
return bits.ToString();
}
รองรับ Negative Numbers (Two's Complement)
public static string ToBinarySigned(int n)
{
if (n >= 0) return Convert.ToString(n, 2);
// สำหรับ Negative: ใช้ 32-bit Two's Complement
return Convert.ToString(n & 0xFFFFFFFF, 2).PadLeft(32, '0');
}
กรณีใช้งาน Recursion จริง
- Algorithm Education: สอนแนวคิด Recursion, Base Case, Recursive Case
- Tree/Graph Traversal
- Divide & Conquer Algorithms (Merge Sort, Quick Sort)
- Backtracking Problems (N-Queens, Sudoku)
⚠️ ข้อควรระวัง
Recursion ใน C# มีขีดจำกัด Stack (~1MB default) การแปลงเลขใหญ่ (เช่น Int32.MaxValue) จะ Recursion ลึก ~31 ระดับ - ปลอดภัย แต่ถ้าเป็น BigInteger หรือ Loop ลึกอาจเกิด StackOverflowException