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

โปรแกรม Java หาผลรวมหลักของเลขด้วย Recursion


ในบทความนี้ เราจะทำความเข้าใจวิธี หาผลรวมของตัวเลขแต่ละหลัก (Sum of Digits) ด้วย Recursion

ตัวอย่าง: 12131415 → 1+2+1+3+1+4+1+5 = 18

ตัวอย่าง Input และ Output

Input:

Enter the number : 12131415

Output:

The Sum of digits of 12131415 is 18

อัลกอริธึม

ขั้นตอนที่ 1 - เริ่มต้น
ขั้นตอนที่ 2 - ประกาศตัวแปร my_input, my_result
ขั้นตอนที่ 3 - อ่านค่าจากผู้ใช้ หรือกำหนดค่าเริ่มต้น
ขั้นตอนที่ 4 - สร้างฟังก์ชัน digitSum แบบ recursive รับตัวเลข คืนค่าผลรวมหลัก
ขั้นตอนที่ 5 - เรียกฟังก์ชันและเก็บผลลัพธ์
ขั้นตอนที่ 6 - แสดงผลลัพธ์
ขั้นตอนที่ 7 - หยุด

ตัวอย่างที่ 1: รับค่าจากผู้ใช้

import java.util.Scanner;
public class Sum {
    public static void main(String args[]) {
        int my_input, my_result;
        System.out.println("Required packages have been imported");
        Scanner my_scanner = new Scanner(System.in);
        System.out.println("A reader object has been defined");
        System.out.print("Enter the number : ");
        my_input = my_scanner.nextInt();
        my_result = digitSum(my_input);
        System.out.println("The Sum of digits of " + my_input + " is " + my_result);
    }
    static int digitSum(int n) {
        if (n == 0)
            return 0;
        return (n % 10 + digitSum(n / 10));
    }
}

Output

Required packages have been imported
A reader object has been defined
Enter the number : 12131415
The Sum of digits of 12131415 is 18

ตัวอย่างที่ 2: กำหนดค่าไว้ล่วงหน้า

public class Sum {
    public static void main(String args[]) {
        int my_input = 12131415;
        System.out.println("The number is defined as : " + my_input);
        int my_result = digitSum(my_input);
        System.out.println("The Sum of digits of " + my_input + " is " + my_result);
    }
    static int digitSum(int n) {
        if (n == 0)
            return 0;
        return (n % 10 + digitSum(n / 10));
    }
}

Output

The number is defined as : 12131415
The Sum of digits of 12131415 is 18