There is challenge on code wars to calculate how many times you have to multiply a Long's individual integers against each other before it becomes a single digit. for example
39 -> 3 * 9 = 27 -> 2 * 7 = 14 -> 1 * 4 = 4 // answer is 3
Here is one of the posted solutions -
class Persist {
public static int persistence(long n) {
int times = 0;
while (n >= 10) {
n = Long.toString(n).chars().reduce(1, (r, i) -> r * (i - '0'));
times++;
}
return times;
}
}
I am very confused by the "(i - '0')" portion of the code. I just learned yesterday that Java's chars() method returns an IntStream which represent the chars so immediately using the reduce makes sense to me. But then it substracts a character which throws me off because it seems to apply that it is working with chars, but then how are they being multiplied together?
I copied the above code and then deleted the character subtraction so that is was a simple reduce statement that I understood, aka
n = Long.toString(n).chars().reduce(1, (r, i) -> r * i);
and then ran the debugger. The very first loop calculated 3 * 9 as 2907. Where does that answer come from? My best guess is that it has to do with character encoding but then why does subtracting the char '0' fix it?