My teacher sent me the following exercise in class, but the teacher didn't even bother to explain how he wanted us to build the code.
The code has to be in java, but it is the same if you can help me with an example in C I can understand it.
I have the following code:
Well the code is quite easy, I take a long, and I divide it between 10, until it is 0, and I add 1 to it.
But the problem is that if the digit I passed is 0, the function returns 0, but there is the problem since 0 is a digit, it would have to return 1.
But our teacher does not say anything about 0, but if I say that count is equal to 1, then when I pass a 0, it returns 1, which would be correct, but if I put another number it would return a count of more example if I put 123 me returns 4.
How could this problem be solved? Recursively if possible. I don't know how to take the problem.
Thanks.
The code has to be in java, but it is the same if you can help me with an example in C I can understand it.
I have the following code:
Java:
public static int countDigitsRecursive(long num) {
int count = 0;
if (num != 0) {
return 1 + countDigitsRecursive(num / 10);
}
return count;
}
Well the code is quite easy, I take a long, and I divide it between 10, until it is 0, and I add 1 to it.
But the problem is that if the digit I passed is 0, the function returns 0, but there is the problem since 0 is a digit, it would have to return 1.
But our teacher does not say anything about 0, but if I say that count is equal to 1, then when I pass a 0, it returns 1, which would be correct, but if I put another number it would return a count of more example if I put 123 me returns 4.
How could this problem be solved? Recursively if possible. I don't know how to take the problem.
Thanks.