Home  >  Article  >  Backend Development  >  In C++, translate the nth number such that the sum of the numbers is ten

In C++, translate the nth number such that the sum of the numbers is ten

WBOY
WBOYforward
2023-09-05 08:41:04942browse

In C++, translate the nth number such that the sum of the numbers is ten

The numbers whose sum is equal to 10 include

19, 28, 37, 46, 55, 64, 73, 82, 91, etc.,

If you look at this sequence, each number adds 9. In the above sequence, during the process of adding 9, there are some numbers whose digit sum does not equal 10. However, you will get the sum of all numbers equal to 10.

So we can have a loop that increments by 9 and checks the sum of numbers and finds the nth number. Let’s see some examples

Input

3
7

Output

37
73

Algorithm

  • Initialization The number n
  • initializes the counter to 0.
  • Write a loop starting from 19
    • If the current sum of numbers is 10, then increment the counter by 1.
    • If the counter is equal to n, return the current number.
    • Increase the iteration variable by 9.

Implementation

The following is the C implementation of the above algorithm
#include <bits/stdc++.h>
using namespace std;
int findNthNumber(int n) {
   int count = 0, i = 19;
   while (true) {
      int sum = 0;
      for (int number = i; number > 0; number = number / 10) {
         sum = sum + number % 10;
      }
      if (sum == 10) {
         count++;
      }
      if (count == n) {
         return i;
      }
      i += 9;
   }
   return -1;
}
int main() {
   int n = 7;
   cout << findNthNumber(7) << endl;
   return 0;
}

Output

If you run the above code, you You will get the following result.

73

The above is the detailed content of In C++, translate the nth number such that the sum of the numbers is ten. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete