CheckDigit
is #1 from the from the 2020 AP Computer Science A Course Description sample problems.
2020 AP CS A Course Description
The sample free response start on PDF page 206 (labeled page 199 at the bottom right). If this link has been redirected to the 2025 Course Description, please let me know as a comment on this page.
Part (a) getCheck
method
public static int getCheck(int num)
{
int sum = 0;
int numDigits = getNumberOfDigits(num);
for(int n = 1; n <= numDigits; n++)
sum += getDigit(num, n) * (8 - n);
return sum % 10;
}
Part (b) isValid
method
public static boolean isValid(int numWithCheckDigit)
{
int number = numWithCheckDigit / 10;
int checkDigit = numWithCheckDigit % 10;
return getCheck(number) == checkDigit;
}
Java files with test code
CheckDigitTest.java includes JUnit 5 test code with the examples from the problem. See Running JUnit 5 tests. CheckDigit.java includes working implementations of getNumberOfDigits
and getDigit
.
CheckDigit.java
CheckDigitTest.java
2020 AP CS A Course Description Free Response Solutions
Help & comments
Get help from AP CS Tutor Brandon Horn
See an error? Question? Please comment below.