So how do we stutter one-digit numbers? To turn a digit n into nn, we'd need to do something like this:
n0 10 of n
n plus 1 of n
--
nn
So we need a total of 11 times n. Some people saw this without thinking about
individual digits and it's pretty obvious when you think about it that 1 times
11 is 11, 2 times 11 is 22, 3 times 11 is 33, and so on. I said to assume for
now a precondition that n is greater than or equal to 0. So we have our base
case:
//pre : n >= 0
public int stutter(int n) {
if (n < 10)
return 11 * n;
else
return ...;
}
So what do we do with numbers like 348? We need some way to break it up into
smaller chunks, a way to split off one or more digits. Someone suggested that
division by 10 would help:
n = 348
34 | 8
-------+-------
n / 10 | n % 10
What next? Here you have to think recursively. The original number was 348.
We've split it up into 34 and 8. What if we stuttered those values? You have
to make the leap of faith and believe that the method actually works. If it
does, then it turns 34 into 3344 and 8 into 88. How do we combine them to get
334488? We can't do simple addition:
3344
88
----
wrong
We need to shift the 88 over to the right relative to the 3344. We do this by
multiplying 3344 by 100:
334400
88
------
334488
But that means we've solved the problem:
//pre : n >= 0
public int stutter(int n) {
if (n < 10)
return 11 * n;
else
return 100 * stutter(n / 10) + stutter(n % 10);
}
I mentioned that the final version of the method in Stutter.java includes an extra case for negative
numbers. So we remove the precondition and add a case for negative n. For a
number like -348, we return -334488 by stuttering the positive number (stutter
348) and then negating the result.