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

โปรแกรมเรียกซ้ำพิมพ์ตัวเลขน้อยกว่า N ที่ประกอบด้วยเลข 1 และ 3 เท่านั้นใน C++


เราได้รับตัวแปรจำนวนเต็ม N เก็บค่าบวก งานคือพิมพ์ตัวเลขทั้งหมดที่น้อยกว่า N และประกอบด้วยเลข 1, 3 หรือการรวมของทั้งสองเท่านั้น แบบเรียกซ้ำ (recursive)

ตัวอย่างการทำงาน (Input/Output)

ตัวอย่างที่ 1

Input: int num = 40

Output: Recursive program to print all numbers less than N which consist of digits 1 or 3 only are: 33 31 13 11 3 1

คำอธิบาย: ตัวเลข < 40 ที่ประกอบด้วย 1,3 เท่านั้น: 1, 3, 11, 13, 31, 33 (พิมพ์จากมากไปน้อย)

ตัวอย่างที่ 2

Input: int num = 5

Output: Recursive program to print all numbers less than N which consist of digits 1 or 3 only are: 3 1

คำอธิบาย: ตัวเลข < 5 คือ 1 และ 3

ตัวอย่างที่ 3

Input: int num = 1

Output: Wrong Input

คำอธิบาย: ไม่มีจำนวนเต็มบวกน้อยกว่า 1 ที่ประกอบด้วย 1 หรือ 3

อัลกอริทึมที่ใช้

  • รับค่า num ส่งให้ Recursive_Numbers(num)
  • ภายใน Recursive_Numbers(num):
    • check = true, temp = num
    • ถ้า num > 0:
      • วน while (temp > 0 && check): ดึงหลักสุดท้าย digit = temp % 10
      • ถ้า digit != 1 && digit != 3 ให้ check = false
      • temp /= 10
      • ถ้า check ยังเป็น true ให้พิมพ์ num
      • เรียกซ้ำ Recursive_Numbers(num - 1)

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

#include <iostream>
using namespace std;

void Recursive_Numbers(int num) {
    bool check = true;
    int temp = num;
    if (num > 0) {
        while (temp > 0 && check) {
            int digit = temp % 10;
            if (digit != 1 && digit != 3) {
                check = false;
            }
            temp = temp / 10;
        }
        if (check) {
            cout << num << " ";
        }
        Recursive_Numbers(num - 1);
    }
}

int main() {
    int num = 40;
    if (num <= 1) {
        cout << "Wrong input";
    } else {
        cout << "Recursive program to print all numbers less than N which consist of digits 1 or 3 only are: ";
        Recursive_Numbers(num);
    }
    return 0;
}

ผลลัพธ์

การรันโค้ดข้างต้นจะได้ผลลัพธ์ดังนี้:

Recursive program to print all numbers less than N which consist of digits 1 or 3 only are: 33 31 13 11 3 1