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>();

int numRemaining = num / 10;
while(numRemaining > 0)
{
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;
}
```

## 11 thoughts on “Digits free response answer”

1. Ryan

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

• Brandon Horn

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.

• Brandon Horn

You could use autoboxing without issue here.

3. Mark Moylan

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.

```public Digits(int num){
digitList = new ArrayList<Integer>();
String snum = "" + num;
for(i = 0; i < snum.length(); i++){
}
}
```
4. Noah

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

• Brandon Horn

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.

5. David

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?

• Brandon Horn

Yes.

Interestingly, the same would not be true of using `==` instead of the `equals` method in a similar circumstance.

6. Reed

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)?

• Brandon Horn

The loop condition is `i < digitList.size()`. The loop would never run for a number with only one digit.