使用 C++ 列印所有 n 位數,其中偶數位數字之和與奇數位數字之和的絕對差為 1
在這個問題中,我們給定一個整數 n,我們必須列印所有 n 位數,使得數字在偶數位和奇數位上的數字之和的絕對差為 1。建立數字時,不考慮前導 0。
**絕對差**是兩個數字之差的絕對值(正值)。
讓我們來看一個例子來理解這個問題:
Input: n = 2 Output: 10 12 21 23 32 34 43 45 54 56 65 67 76 78 87 89 98 Explaination : taking an of the numbers from the output, 54, even digit - odd digit = 5 - 4 = 1 89, even digit - odd digit = 8 - 9 = -1 , |-1| = 1.
為了解決這個問題,我們必須找到所有差為 1 或 -1 的 n 位數。為此,我們將用所有值固定一個數字位置,並根據其位置是偶數還是奇數,呼叫數字中其他位置的值,以滿足條件。
示例
下面的程式將演示我們的解決方案:
#include <iostream> using namespace std; void printNumber(int n, char* out, int index, int evenSum, int oddSum){ if (index > n) return; if (index == n){ if (abs(evenSum - oddSum) == 1) { out[index] = ' '; cout << out << " "; } return; } if (index & 1) { for (int i = 0; i <= 9; i++) { out[index] = i + '0'; printNumber(n, out, index + 1, evenSum, oddSum + i); } } else { for (int i = 0; i <= 9; i++) { out[index] = i + '0'; printNumber(n, out, index + 1, evenSum + i, oddSum); } } } int findNumberWithDifferenceOne(int n) { char out[n + 1]; int index = 0; int evenSum = 0, oddSum = 0; for (int i = 1; i <= 9; i++) { out[index] = i + '0'; printNumber(n, out, index + 1, evenSum + i, oddSum); } } int main() { int n = 3; cout<<n<<" digit numbers with absolute difference 1 : \n"; findNumberWithDifferenceOne(n); return 0; }
輸出
3 digit number with absolute difference 1 − 100 111 120 122 131 133 142 144 153 155 164 166 175 177 186 188 197 199 210 221 230 232 241 243 252 254 263 265 274 276 285 287 296 298 320 331 340 342 351 353 362 364 373 375 384 386 395 397 430 441 450 452 461 463 472 474 483 485 494 496 540 551 560 562 571 573 582 584 593 595 650 661 670 672 681 683 692 694 760 771 780 782 791 793 870 881 890 892 980 991
廣告