打印所有n位数字,C ++中偶数和奇数之和的绝对差为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