使用 C++ 列印所有 n 位數嚴格遞增的數字
本例題中,給定一個數 N,要求列印所有 *n 位數*,且各位數字從高位到低位嚴格單調遞增,即最低位 (左) 數字應小於其右邊的數字。
我們透過一個例子來理解一下本題——
輸入——n = 2
輸出——
01 02 03 04 05 06 07 08 09 12 13 14 15 16 17 18 19 23 24 25 26 27 28 29 34 35 36 37 38 39 45 46 47 48 49 56 57 58 59 67 68 69 78 79 89.
解釋——如你所見,所有數字的左邊的數字都比其右邊的數字小。
要解決本題,我們將從 MSB(左位)開始依次輸入數字,然後根據條件生成數字。下一個位置將包含 i+1 至 9 的數字,其中 i 是當前位置的數字。
用於實現程式碼邏輯的程式碼——
示例
#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; }
輸出
All 3 digit strictly increasing numbers are − 012 013 014 015 016 017 018 019 023 024 025 026 027 028 029 034 035 036 037 038 039 045 046 047 048 049 056 057 058 059 067 068 069 078 079 089 123 124 125 126 127 128 129 134 135 136 137 138 139 145 146 147 148 149 156 157 158 159 167 168 169 178 179 189 234 235 236 237 238 239 245 246 247 248 249 256 257 258 259 267 268 269 278 279 289 345 346 347 348 349 356 357 358 359 367 368 369 378 379 389 456 457 458 459 467 468 469 478 479 489 567 568 569 578 579 589 678 679 689 789
廣告