Digits free response problem from the 2017 AP Computer Science A Exam.

Digits is #1 from the from the 2017 AP Computer Science A Free Response problems.

https://secure-media.collegeboard.org/ap/pdf/ap-computer-science-a-frq-2017.pdf

## Part (a) – Digits constructor

Adding to the beginning of an ArrayList isn’t my favorite approach, since all of the elements have to shift. Given the simplicity though, I think it’s a reasonable tradeoff.

This is both my time constrained and considered approach.

```
public Digits(int num)
{
digitList = new ArrayList<Integer>();
digitList.add(0, new Integer(num % 10));
int numRemaining = num / 10;
while(numRemaining > 0)
{
digitList.add(0, new Integer(numRemaining % 10));
numRemaining /= 10;
}
}
```

## Part (b) – isStrictlyIncreasing method

The use of compareTo here is optional. Java will automatically unbox the Integer objects into primitive types if >= is used.

This is both my time constrained and considered solution.

```
public boolean isStrictlyIncreasing()
{
for(int i = 1; i < digitList.size(); i++)
if(digitList.get(i - 1).compareTo(digitList.get(i)) >= 0)
return false;
return true;
}
```

## 2017 AP CS Exam Free Response Solutions

Please note: The College Board has not yet released scoring guidelines for the 2017 AP CS A FR (as of this writing). Questions of the form, “How many points would I lose for ___?” can’t be answered.

In Part a, you need to test for when num == 0 and then do digitList.add(0).

The line

`digitList.add(0, new Integer(num % 10));`

handles 0 without the need to explicitly check for it. If`num`

is 0 then`num % 10`

is 0.Do you need “new Integer” ? I thought auto boxing already did this, so on mine I just used ints.

You could use autoboxing without issue here.

This is another approach, but it does step outside the AP subset, because it doesn’t cover the Integer constructor that takes a string, and has the same behavior as parse int.

It doesn’t look like your code in part a checks for when a number ends in 0. Correct me if I’m wrong.

While it is necessary to handle numbers that end in 0 it isn’t necessary to check for them explicitly. My code in part (a) handles numbers that end in 0 on the 2nd line.

I didn’t use .compareTo(), but just used a >= symbol. Will this lose me points? Isn’t it still valid code because the Integer objects get unboxed into primitive ints?

Yes.

Interestingly, the same would not be true of using

`==`

instead of the`equals`

method in a similar circumstance.In part b, if isStrictlyIncreasing() were called upon a number with only one digit (7, for example), wouldn’t there be an indexOutOfBoundsException when you look at index 1 in digitList (since there is only one number at index 0)?

The loop condition is

`i < digitList.size()`

. The loop would never run for a number with only one digit.