
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
N-th Number Whose Sum of Digits is Ten in C++
The numbers whose digits sum is equal to 10 are
19, 28, 37, 46, 55, 64, 73, 82, 91, etc..,
If you observe the series, each number is incremented by 9. There are numbers in the above sequence whose digits sum does not equal 10 while incrementing by 9. But, you will get all the numbers whose digits sum is equal to 10.
So, we can have a loop that increments by 9 and checks for digits sum and finds the n-th number. Let's see some examples
Inputs
3 7
Outputs
37 73
Algorithm
- Initialise the number n
- Initialise a counter to 0.
- Write a loop that iterates from 19
- If the current number digits sum is 10, increment the counter by 1.
- If the counter is equal to n, then return the current number.
- Increment the iterative variable by 9.
Implementation
Following is the implementation of the above algorithm in C++
#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, then you will get the following result.
73
Advertisements