Skip to content

Instantly share code, notes, and snippets.

@bhnascar
Created March 12, 2017 22:02
Show Gist options
  • Save bhnascar/b9919877434624587179040382b503c6 to your computer and use it in GitHub Desktop.
Save bhnascar/b9919877434624587179040382b503c6 to your computer and use it in GitHub Desktop.
Code reading practice
import java.util.*;
class ReadingPractice
{
/* What is the return value of |mystery("hi")|?
*
* (A) hi
* (B) hi5
* (C) hi55
* (D) mn
* (E) This doesn't compile
*/
public String mystery(String input) {
String output = "";
for (int i = 0; i < input.length(); i++) {
output += (char)(input.charAt(i) + 5);
}
return output;
}
/* Which of the following values of num will make
* checkDigit(num) return true?
*
* (A) 6153
* (B) 6154
* (C) 6155
* (D) 6156
* (E) 6157
*/
public boolean checkNumber(int n) {
int checkDigit = n % 10;
int d1 = (n / 10) % 10;
int d2 = (n / 100) % 10;
int d3 = (n / 1000) % 10;
int remainder = (d1 + d2 + d3) % 7;
return checkDigit == remainder;
}
/* What is the result of mystery(arr) if arr contains
* ["Hi", "there", "Benjamin!"]
*
* (A) "That's all!"
* (B) "Hi there Benjamin That's all!"
* (C) "That's all! Benjamin there Hi"
* (D) "That's all!BenjaminthereHi"
* (E) No output.
*/
public void mystery(ArrayList<String> words) {
if (words.size() == 0) {
System.out.print("That's all!");
}
else {
String word = words.get(0);
words.remove(0);
mystery(words);
System.out.print(word);
}
}
/* What is the result of mystery(2513560)?
*
* (A) 2513560
* (B) 251356
* (C) 065315
* (D) 0653152
* (E) Infinite recursion
*/
public void mystery(int n) {
System.out.print(n % 10);
if (n >= 10) {
mystery(n / 10);
}
}
/* Given an int array arr, What does the method |recur(arr, arr.length)|
* do? Assume that n is always within bounds.
*
* (A) It finds the largest value in arr and leaves arr unchanged.
* (B) It finds the smallest value in arr and leaves arr unchanged.
* (C) It sorts arr in ascending order and returns the largest value.
* (D) It sorts arr in descending order and returns the largest value.
* (E) It returns arr[0] or arr[1], whichever is larger.
*/
public int recur(int[] input, int n) {
if (n == 1) {
return input[0];
}
else {
int result = recur(input, n - 1);
if (input[n - 1] > result) {
return input[n - 1];
}
else {
return result;
}
}
}
/* Test code. */
public static void main(String[] args) {
ReadingPractice practice = new ReadingPractice();
// Test.
System.out.println(practice.mystery("hi"));
System.out.println(practice.checkNumber(6155));
ArrayList<String> testWords = new ArrayList<String>();
testWords.add("Hi");
testWords.add("there");
testWords.add("Benjamin");
practice.mystery(testWords);
System.out.println();
practice.mystery(2513560);
System.out.println();
int[] arr = new int[]{6, 1, 3, 2, 3, 4, 8, 4};
System.out.println(practice.recur(arr, arr.length));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment