Nth number whose sum of digits is 10

By | December 11, 2022

Given, write a program that prints the Nth number whose sum of digits is 10.

Examples:

Input : 2
Output : 28 
Explanation : the first number is 19, whose digit sum is 10. 

Input : 5 
Output : 55  
Explanation : the first four numbers whose digit sum is 10 are 
              19,28,37,46.

Approach: In order to obtain the Nth number whose sum of digits is 10, we start iterating from i=18 and keep a count for all numbers whose digit sum returns 10. When the count is N, we return the value of i at that instant.

Below is the implementation of the above approach:

// CPP program to print the Nth 
// number whose sum of digits is 10 
//#include <bits/stdc++.h>
#include<iostream>
using namespace std;
#define ll long long

// function to check if the sum of digit 
// is 10 or not 
int isTen(int n){
    
	int sum = 0; 
	
	// calculates the sum of digits 
	while (n){
		sum += n%10;
		n /= 10;
	}
    
    // returns 1 if sum of digits is 10 
    // returns 0 is sum of digits is not 10 
	return (sum==10);
}

// function that returns the N-th number 
// whose sum of digits is 10 
int getNumber(int n)
{
    int count = 0;
    
    // iterate from 19 till we get out Nth number 
    for (int i = 19 ; ; i++)
    {
        if (isTen(i) == 1)
        {
            // increase count 
            count++; 
            
            // return the N-th number
            if (count == n) 
               return i;
        }
    }
}

// Driver Code
int main(){
	int N = 8; 
	cout << getNumber(N);

	return 0;
}

Output:

82

Time Complexity:

O(1)

Please write comments if you find anything incorrect. A gentle request to share this topic on your social media profile.

Author: Mithlesh Upadhyay

I hold an M.Tech degree in Artificial Intelligence (2023) from Delhi Technological University (DTU) and possess over 4 years of experience. I worked at GeeksforGeeks, leading teams and managing content, including GATE CS, Test Series, Placements, C, and C++. I've also contributed technical content to companies like MarsDev, Tutorialspoint, StudyTonight, TutorialCup, and Guru99. My skill set includes coding, Data Structures and Algorithms (DSA), and Object-Oriented Programming (OOPs). I'm proficient in C++, Python, JavaScript, HTML, CSS, Bootstrap, React.js, Node.js, MongoDB, Django, and Data Science.