Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

หาผลรวมของหลักเลข (Sum of Digits) ด้วย Recursion ใน C#

ภาพรวม

ใช้ Recursion หาผลรวมของตัวเลขแต่ละหลัก เช่น 123 = 1+2+3 = 6

โค้ดตัวอย่าง


using System;

class Demo {
    public static void Main(string[] args) {
        int n = 22;
        int result = SumOfDigits(n);
        Console.WriteLine($"Number = {n}");
        Console.WriteLine($"Sum of digits = {result}"); // 4
    }

    static int SumOfDigits(int n) {
        if (n == 0) return 0;
        return (n % 10) + SumOfDigits(n / 10);
    }
}

ผลลัพธ์


Number = 22
Sum of digits = 4

การทำงานของ Recursion

SumOfDigits(22)
= 22%10 + SumOfDigits(22/10)
= 2 + SumOfDigits(2)
= 2 + (2%10 + SumOfDigits(2/10))
= 2 + (2 + SumOfDigits(0))
= 2 + (2 + 0)
= 4

รองรับเลขลบ


static int SumOfDigits(int n) {
    n = Math.Abs(n); // จัดการเลขลบ
    if (n == 0) return 0;
    return (n % 10) + SumOfDigits(n / 10);
}

วิธี Iterative (แนะนำสำหรับ Production)


static int SumOfDigitsIterative(int n) {
    n = Math.Abs(n);
    int sum = 0;
    while (n > 0) {
        sum += n % 10;
        n /= 10;
    }
    return sum;
}

วิธี LINQ (สั้นที่สุด)


using System.Linq;

int sum = n.ToString().Where(char.IsDigit).Sum(c => c - '0');
// หรือ
int sum = Math.Abs(n).ToString().Select(c => c - '0').Sum();

Digital Root (รวมจนเหลือ 1 หลัก)


static int DigitalRoot(int n) {
    n = Math.Abs(n);
    if (n == 0) return 0;
    return 1 + (n - 1) % 9; // Mathematical formula
}

// หรือ Recursive
static int DigitalRootRecursive(int n) {
    n = Math.Abs(n);
    int sum = SumOfDigits(n);
    return sum < 10 ? sum : DigitalRootRecursive(sum);
}

สรุปประสิทธิภาพ

วิธีTimeSpaceหมายเหตุ
RecursiveO(d)O(d) stackd = จำนวนหลัก, อาจ StackOverflow ถ้าหลักมาก
IterativeO(d)O(1)แนะนำสำหรับ Production
LINQO(d)O(d)สร้าง string, ใช้ memory มากกว่า
Math Formula (Digital Root)O(1)O(1)เฉพาะ Digital Root