Spring 2024 [Bono]

CS 455 Midterm 1 Solution


Problem 1
Part A [7].


Part B [3].

[21, 16] [21, 16] [21, 16]


Problem 2
Many correct solutions.

1. (wrong)     str: "ab?";    return value: -1
2. (right)     str: "abc";    return value: 2


Problem 3
Solution shown in bold.

// DigitExtractor breaks up a positive integer into its individual digits.
public class DigitExtractor {   
  
   private int num;
   private int currPow;


   // Creates digit extractor for the given integer.
   // @param anInt the integer to extract from
   // PRECONDITION: anInt > 0
   public DigitExtractor (int anInt) {
 
      num = anInt;
      currPow = largestPowerOf10(num);

   }

   // Returns true iff there are more digits left to extract.
   public boolean hasNextDigit() {
 
      return currPow > 0;

   }

   // Extracts the the "next" digit in the integer (starts from leftmost
   // (most significant) digit, and goes rightward)
   // PRECONDITION: hasNextDigit()
   // @return the digit
   public int nextDigit() {
 
       int currDig = num / currPow;
       num = num % currPow;
       currPow = currPow / 10;
       return currDig;

   }
}


Problem 4   

mkdir practice
cp $ASNLIB/public/02-08/* practice


Problem 5
There was no problem 5. (mistake on exam)


Problem 6
Changes shown in bold.

Part A.

public class Circle {
   
   private double radius;
   private double circumference;

   public Circle(double radius) {
      this.radius = radius;
      this.circumference = 2.0 * Math.PI * radius;
   }

   public double getRadius() {
      return radius;
   }

   public double getCircumference() {
      return circumference;
   }

   public void shrink() {
      radius = radius / 2.0;
      circumference = 2.0 * Math.PI * radius;
   }
}

Part B.
public class Circle {
   
   private double radius;
   private double circumference;

   public Circle(double radius) {
      this.radius = radius;
      this.circumference = 2.0 * Math.PI * radius;
   }

   public double getRadius() {
      return radius;
   }

   public double getCircumference() {
      return circumference 2.0 * Math.PI * radius;;
   }

   public void shrink() {
      radius = radius / 2.0;
   }

Problem 7
Several variations depending on how you do your loop bounds and loop variables, but they all amount to shifting the same elements the same distance to the left.

   public static int removeChunk(int[] nums, int size, int start, int end) {

      int numToRemove = end - start;
      int numToShift = size - end;

      for (int i = 0; i < numToShift; i++) {
         nums[i + start] = nums[i + end];
      }
      return size - numToRemove;
   }