I am trying to solve the problem. Is my logic correct?
No, you shouldn't sum the input value.
Program::solution(16) is supposed to return 79. So you should sum the digits in the loop on line 26 and return the value who's digit sum (for 16 -> 79 = 7 + 9) equals the input value (16)
there is probably some math answer that takes staring at it for a while to figure out, but at the very least, you can do this:
16 -1 is 15 and 1
16 - 2 is 14 and 2
... 16-9 is 9 and 7
16-10 is 10 and 6
...
there are only 16 sums including zero. But the ones with 2 digits are invalid, right?
since you only need to handle 0-50, the best answer is a lookup table of the answers :)
but pick any number, 47 for example.
now, you know that 9+9+9 is 27. 9+9+9+9, still too small. 5x9 is 45, too small. so its a 6 digit number. 45+2, actually. 299999, perhaps? See any algorithm you can use there? You can find the number of digits needed... and from there, figure out what those digits must be.
trying 16 that way, its < 9+9 and > 9 so 2 digits expected.
16-9 is 7, so you have your 7 and 9 digits, but is that best?
decrement the 9, increment the 7, 8 and 8 is the only other candidate.
so 97, 79, 88 ... which one?
#include <iostream>
#include <string>
usingnamespace std;
int solution1( int N )
{
return N >= 9 ? 9 + 10 * solution1( N - 9 ) : N;
}
int solution2( int N )
{
return stoi( to_string( N % 9 ) + string( N / 9, '9' ) );
}
int main()
{
for ( int i = 0; i <= 50; i++ ) cout << i << '\t' << solution1( i ) << '\t' << solution2( i ) << '\n';
}
Why a class? Why static members?
I think that it's because @leo2008 and @denver2020 are trying to copy java solutions that they have found elsewhere.