Learn AP Comp Sci

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?

  1. returns a String representation of the digits in n, left to right, separated by commas
  2. returns a String representation of the digits in n, right to left, separated by commas
  3. returns the first and last digits of n, separated by a comma
  4. results in a StackOverflowError because the recursion never ends

Show solution:

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.