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

หาตัวเลขลำดับที่ n ที่มีหลัก k หรือหาร k ลงตัวใน C++

ได้รับจำนวนเต็มบวกสองจำนวน n และ k เราต้องหาตัวเลขลำดับที่ n ที่มีหลัก k หรือหาร k ลงตัว k จะอยู่ในช่วง [2 ถึง 9] ดังนั้นถ้า n และ k เป็น 15 และ 3 ตามลำดับ ผลลัพธ์คือ 33 ตัวเลข [3, 6, 9, 12, 13, 15, 18, 21, 23, 24, 27, 30, 31, 33] นี่คือตัวเลขที่แต่ละองค์ประกอบมีหลัก k = 3 หรือหาร k ลงตัว และตัวเลขลำดับที่ n คือ 33 ดังนั้นผลลัพธ์คือ 33

ตรวจสอบแต่ละตัวเลขว่ามีหลัก k และเป็นตัวคูณของ k แล้วนับจนกว่าจะได้องค์ประกอบลำดับที่ n

ตัวอย่าง

#include <iostream> 
using namespace std; 

bool hasDigit(int n, int k) {
    while (n > 0) {
        int rem = n % 10;
        if (rem == k)
            return true;
        n = n / 10;
    }
    return false;
}

int countNumbers(int n, int k) {
    for (int i = k + 1, count = 1; count < n; i++) {
        if (hasDigit(i, k) || (i % k == 0))
            count++;
        if (count == n)
            return i;
    }
    return -1;
}

int main() {
    int n = 10, k = 2;
    cout << "Last number is " << countNumbers(n, k) << " before that the number contains " << k << " and multiple of " << k;
}

ผลลัพธ์

Last number is 20 before that the number contains 2 and multiple of 2