Count of all N digit numbers such that num + Rev(num) = 10^N - 1 in C++

C++Server Side ProgrammingProgramming

Given a number N as input. The goal is to find the count of all N digit numbers that have sum Count of all N digit numbers such that num + Rev(num) = 10N − 1

num+rev(num)=10N−1

For Example

Input

N=4

Output

Count of all N digit numbers such that num + Rev(num) = 10N − 1 are − 90

Explanation

The numbers would be −

1. 1188 + 8811 = 9999
2. 2277 + 7722 = 9999
3. 1278 + 8721 = 9999
……...total 90 numbers

Input

N=5

Output

Count of all N digit numbers such that num + Rev(num) = 10N − 1 are − 0

Explanation

As N is odd, there will be no such number as the middle element will be
added to itself and cannot have sum as 9.
Ex. 148+841=989

Approach used in the below program is as follows

For any N digit number the sum of it with reverse will be 9N−1 = 999..N times if sum of individual digits in both numbers and its reverse is 9. In case of odd N, the middle digit will be added to itself. As no same whole numbers have sum 9 so the answer will be 0.In case of even N, the pairs of 1st−Nth, 2nd−N−1th, 3rd−N−2th.. Digits will have to be 9. Possible pairs will be (1+8), (2+7), (3+6), (4+5), (5+4) ,(6+3), (7+2), (8+1), (9+0). Answer will be 9*10N/2 − 1

  • Take an integer N as input.

  • Function digit_numbers(int N) takes N and returns count of all N digit numbers such that num + Rev(num) = 10^N − 1.

  • Take the initial count as 0.

  • If N is odd, then N%2 is 1. Return 0.

  • Else set count = 9 * pow(10, N/2 − 1).

  • Return count as result.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int digit_numbers(int N){
   int count = 0;
   if (N % 2 == 1){
      return 0;
   } else {
      count = 9 * pow(10, N/2 − 1);
   }
   return count;
}
int main(){
   int N = 4;
   cout<<"Count of all N digit numbers such that num + Rev(num) = 10^N − 1 are: "<<digit_numbers(N);
   return 0;
}

Output

If we run the above code it will generate the following output −

Count of all N digit numbers such that num + Rev(num) = 10^N − 1 are: 90
raja
Published on 05-Jan-2021 06:59:33
Advertisements