2017, Question 1

The full FRQ can be found here

a) Write the constructor for the Digits class.

  • Constructor: initilizes/fills digitList with the digits from num
  • digitList: elements are Integer objects representing single digits, and appear in the same order as the digits in num.

b) Write the Digits method isStrictlyIncreasing.

  • returns true if elements of digitList are strictly increasing in order
  • returns false otherwise
public class Digits { 
    /** The list of digits from the number used to construct this object. 
    * The digits appear in the list in the same order in which they appear in the original number.
    */ 
    private ArrayList<Integer> digitList; 

    /** Constructs a Digits object that represents num.
     * Precondition: num >= 0
    */ 
    public Digits(int num) {
        /* to be implemented in part (a) */ 
    }

    /** Returns true if the digits in this Digits object are in strictly increasing order;
     * false otherwise.
    */ 
    public boolean isStrictlyIncreasing() {
        /* to be implemented in part (b) */ 
    } 
}

My Solution

  • Part a: Convert the original int to a String, then iterate through each char of the String to create an ArrayList of digits. The elements of the final array were converted back into ints.
  • Part b: Iterate through each element of digitList to check if the current element is greater than the previous element.
public class Digits {
    private ArrayList<Integer> digitList;

    // part a - constructor to initialize and fill digitList
    public Digits(int num) {
        this.digitList = new ArrayList<Integer>();
        String numberString = String.valueOf(num);
        char[] chars = numberString.toCharArray();

        for(char ch: chars) {
            this.digitList.add(Character.getNumericValue(ch));
        }

        // to test that the constructor is working
        System.out.println(this.digitList);
    }

    // part b - check if digits are strictly increasing
    public boolean isStrictlyIncreasing() {
        boolean checkIncreasing = true; 
        for(int i = 1; i < this.digitList.size(); i++) {
            if(this.digitList.get(i) > this.digitList.get(i-1)) {
                continue;
            } else {
                checkIncreasing = false;
                break;
            }
        }
        return checkIncreasing;
    }

    public static void main(String[] args) {
        // testing - should return true for isStrictlyIncreasing
        Digits newDigit = new Digits(6789);
        if(newDigit.isStrictlyIncreasing() == false) {
            System.out.println("not strictly increasing");
        } else {
            System.out.println("strictly increasing");
        }
    }
}

Digits.main(null);
[6, 7, 8, 9]
strictly increasing