Home > Backend Development > C++ > 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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2023-09-05 08:41:04
forward
1072 people have browsed it

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
Copy after login

Output

37
73
Copy after login

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

< p>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;
}
Copy after login

Output

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

73
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template