Problem 2
Answer shown in underlined bold.
public class LastNonDigit {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String word = in.next();
boolean found = false;
int position = word.length()-1;
while (!found && position >= 0) {
char ch = word.charAt(position);
if (!Character.isDigit(ch)) {
found = true;
}
else {
position--;
}
}
if (found) {
System.out.println("Last non-Digit: " + word.charAt(position));
System.out.println("Position: " + position);
}
else {
System.out.println("All digits");
}
}
}
Part B [4].
Note: spacing added here for readability.
foo: 1 [0, 1, 0] main1: 0 [0, 1, 0] foo: 2 [0, 1, 1] main2: 1 [0, 1, 1]
Problem 4
Solution shown in bold.
Problem 5
Solution shown in bold.
public class Car {
private int mpg;
private double milesDriven;
private double gasLeft;
public Car(int milesPerGallon) {
mpg = milesPerGallon;
milesDriven = 0;
gasLeft = 0;
}
public double gasLeft() {
return gasLeft;
}
public double milesDriven() {
return milesDriven;
}
public void addGas(double gallons) {
gasLeft += gallons;
}
public double drive(int miles) {
double gasNeeded = miles / (double) mpg;
double actualMiles = miles;
if (gasNeeded > gasLeft) {
actualMiles = gasLeft * mpg;
gasLeft = 0.0;
}
else {
gasLeft -= gasNeeded;
}
milesDriven += actualMiles;
return actualMiles;
}
}
Alternate solution for drive method:
public double drive(int miles) {
double potential = gasLeft * mpg;
double actualMiles = miles;
if (actualMiles > potential) {
actualMiles = potential;
}
gasLeft -= (actualMiles / mpg);
milesDriven += actualMiles;
return actualMiles;
}
Problem 6
Several variations on how to solve this. We'll show two
here.
Solution 1. One-loop solution
public static int[] rotateLeft(int[] nums, int k) {
int[] result = new int[nums.length];
k = k % nums.length; // equivalent smaller rotation
// (optional because of % in loop)
for (int dest = 0; dest < nums.length; dest++) {
result[dest] = nums[(dest + k) % nums.length];
}
return result;
}
Solution 2. Two-loop solution.
public static int[] rotateLeft2(int[] nums, int k) {
int[] result = new int[nums.length];
k = k % nums.length; // convert to a value in [0, nums.length-1]
// shift last part left
int dest = 0;
for (int source = k; source < nums.length; source++) {
result[dest] = nums[source];
dest++;
}
// shift first part right
for (int source = 0; source < k; source++) {
result[dest] = nums[source];
dest++;
}
return result;
}