You are given a positive number ‘N.’ You need to find all the numbers such that the sum of digits of those numbers to the number itself is equal to ‘N.’
For example:You are given ‘N’ as 21, the only number whose sum of digits and the number itself equals 21 is 15 as 15 + 1 + 5 = 21. Hence the answer is [15].
The first line contains a single integer ‘T’ representing the number of test cases.
Each test case consists of a single integer ‘N’, which represents the given integer.
Output Format :
For each test case, print all the space-separated integers whose sum of digits with themselves is equal to ‘N’ in increasing order, Print -1 if no such integer exists.
Print a separate line for each test case.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 10^12
Time Limit: 1 sec
2
21
8
15
4
For the first test case, you are given ‘N’ as 21, the only number whose sum of digits and the number itself equals 21 is 15 as 15 + 1 + 5 = 21. Hence the answer is [15].
For the second test case, you are given ‘N’ as 8, the only number whose sum of digits and the number itself equals 8 is 4 as 4 + 4 = 8. Hence the answer is [4].
2
10
31
5
-1
Think of a brute force approach to solve this problem.
In this approach, we iterate through the numbers from 1 to N. We will find the sum of its digits and add it to the integer itself for each number. Then, we check if the obtained sum is equal to N.
We create a recursive function called sumOfDigits(num) that returns the sum of digits of the number num.
Algorithm:
O(N*log(N)), where N is the given integer.
The time complexity to calculate the sum of digits is O(log(N)). We are calculating the sum of digits of N integers. Hence, the overall time complexity is O(N*log(N))
O(1).
We store an array of integers, but the array will contain very few integers in most cases. Hence, the overall space complexity is O(1).