在 C++ 中查詢包含數字 k 或 k 的公倍數的第 n 個數字
給定兩個正整數 n 和 k,我們需要找到包含數字 k 或 k 的公倍數的第 n 個數字。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
廣告