Problem of the Day
Friday, April 19, 2024
Problem:
Consider the static method next
shown here.
public static String next(int n)
{
if (n / 10 > 0)
return next(n / 10) + "," + n % 10;
else
return "" + n % 10;
}
For a given int
value n
, what does this code do?
- returns a String representation of the digits in
n
, left to right, separated by commas - returns a String representation of the digits in
n
, right to left, separated by commas - returns the first and last digits of
n
, separated by a comma - results in a StackOverflowError because the recursion never ends
The correct answer is a. This function identifies n % 10
each time, the rightmost digit of n
, and if there are more digits to be identified, recursively calls itself. Because of the ordering of strings in the return
statement, the final result is in left-to-right order.