Key to CSE143 Sample Midterm, Winter 2006 handout #20
1. Method Call Value Returned
------------------------------------------
mystery(10, 28) 2
mystery(5, 17) 3
mystery(2, 10) 5
mystery(4, -15) -3
mystery(-3, -23) 7
2. One possible solution appears below.
public static void printTwos(int n) {
if (n < 1)
throw new IllegalArgumentException();
else if (n % 4 == 0) {
System.out.print("2 * ");
printTwos(n / 4);
System.out.print(" * 2");
} else if (n % 2 == 0) {
System.out.print("2 * ");
printTwos(n / 2);
} else {
System.out.print(n);
}
}
3. One possible solution appears below.
public boolean hasTwoConsecutive() {
if (front == null || front.next == null)
return false;
ListNode current = front;
while (current.next != null) {
if (current.data + 1 == current.next.data)
return true;
current = current.next;
}
return false;
}
4. Statement Output
------------------------------------------------------------
var1.method2(); compiler error
var2.method2(); Gulp 2/Gulp 3
var3.method2(); Gulp 2/Sip 3
var4.method2(); Gulp 2/Drink 3
var5.method2(); compiler error
var6.method2(); Gulp 2/Drink 3
var1.method3(); compiler error
var2.method3(); Gulp 3
var3.method3(); Sip 3
var4.method3(); Drink 3
var5.method3(); compiler error
var6.method3(); Drink 3
((Sip)var6).method1(); runtime error
((Gulp)var1).method1(); compiler error
((Gulp)var1).method2(); Gulp 2/Bite 3/Gulp 3
((Bite)var1).method3(); Bite 3/Gulp 3
((Bite)var6).method1(); Bite 1
((Drink)var1).method1(); runtime error
((Drink)var4).method2(); Gulp 2/Drink 3
((Bite)var3).method1(); runtime error
5. Two possible solutions appear below.
public static void rearrange(Queue q) {
Stack s = new ArrayStack();
int oldSize = q.size();
for (int i = 0; i < oldSize; i++) {
int n = q.dequeue();
if (n % 2 == 0)
q.enqueue(n);
else
s.push(n);
}
int evenCount = q.size();
while (!s.isEmpty())
q.enqueue(s.pop());
for (int i = 0; i < evenCount; i++)
q.enqueue(q.dequeue());
for (int i = 0; i < oldSize - evenCount; i++)
s.push(q.dequeue());
while (!s.isEmpty())
q.enqueue(s.pop());
}
public static void rearrange(Queue q) {
Stack s = new ArrayStack();
int oldSize = q.size();
for (int i = 0; i < oldSize; i++) {
int n = q.dequeue();
if (n % 2 == 0)
q.enqueue(n);
else
s.push(n);
}
while (!s.isEmpty())
q.enqueue(s.pop());
for (int i = 0; i < oldSize; i++) {
int n = q.dequeue();
if (n % 2 == 0)
q.enqueue(n);
else
s.push(n);
}
while (!s.isEmpty())
q.enqueue(s.pop());
}
6. One possible solution appears below.
public IntList runningTotal() {
IntList result = new IntList(this.elementData.length);
if (size > 0) {
result.elementData[0] = this.elementData[0];
for (int i = 1; i < this.size; i++)
result.elementData[i] = result.elementData[i - 1]
+ this.elementData[i];
}
result.size = this.size;
return result;
}