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

พิมพ์ตัวเลข N หลักที่เพิ่มขึ้นอย่างเคร่งครัดใน C++

ภาพรวมปัญหา

ได้รับ N ต้องพิมพ์ตัวเลข N หลักที่หลักเพิ่มขึ้นอย่างเคร่งครัดจากซ้ายไปขวา (MSB < LSB)

ตัวอย่าง

Input: n = 2
Output: 01 02 03 ... 89

วิธีแก้ปัญหา (Recursion)

เริ่มจากหลักแรก (MSB) ลอง 0-9 แล้วหลักถัดไปต้อง > หลักก่อนหน้า (i+1 ถึง 9)

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

#include <iostream>
using namespace std;

void printIncresingNumbers(int start, string out, int n) {
    if (n == 0) {
        cout << out << " ";
        return;
    }
    for (int i = start; i <= 9; i++) {
        string str = out + to_string(i);
        printIncresingNumbers(i + 1, str, n - 1);
    }
}

int main() {
    int n = 3;
    cout << "All " << n << " digit strictly increasing numbers are:\n";
    printIncresingNumbers(0, "", n);
    return 0;
}

ผลลัพธ์ (Output)

All 3 digit strictly increasing numbers are:
012 013 014 ... 789