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
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;
}
}
It is very common for students to miss the first line of this constructor. Adding to a list (or setting elements in an array) is not the same thing as initializing the variable.
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.
Part (b) isStrictlyIncreasing
method
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;
}
The use of compareTo
here is optional. Java will automatically unbox the Integer
objects into primitive types if >= is used.
For more on compareTo
see compareTo on the AP CS A Exam.
2017 AP CS Exam Free Response Solutions
Help & comments
Get help from AP CS Tutor Brandon Horn