Says that every single-digit number qualifies as 'digit-increasing' (all single-digit numbers are < 10).
A 'digit-increasing' consists of addition of numbers with the same digit. That digit can be any digit so it could be
0 + 00 + 00 or
1 + 11 + 11 etc.
But 0 + 00 + 00 +.. = 0. And our
if (n < 10)
takes care of this.
So we only need to worry about the digits 1 through 9.
for(int i=1; i<=9; i++)
Let's consider a 'digit-increasing' number formed by the addition of digit 1.
1 + 11 + 111 +...
We can write 1 as: 1
We can write 11 as: 10x1 + 1
We can write 111 as: 10x10x1 + 10x1 + 1
See the pattern? That's essentially what we'll do, programmatically.
So
for(int i=1; i<=9; i++)
is for testing with all digits, not just 1.
int tempsum=i;
int previous=i; |
tempsum will contain the sum (like with 10x1 + 1)
previous will contain the previous power of ten.
while(tempsum<=n)
Makes sure we stop when the sum exceeds n.
1 2 3 4
|
if(tempsum==n)
{
return 1;
}
|
^ If we've found that the sum == n then it's a 'increasing-digit'.
1 2
|
previous = previous*10+i;
tempsum=tempsum+previous;
|
This is the most important part of the code.
What that says is to follow the pattern i + 10*i + 10*10*i +...
See that it is similar to 1 + 11 + 111 +..
That's basically it.