// Program to test solutions to problem #7 on the cse143x midterm, autumn 2013. // Fill in your solution to digitRange, then compile and run the program. import java.util.*; public class Test7 { public static int digitRange(int n) { // fill in your solution here // you can also rename the parameter above } // this is the sample solution public static int digitRange2(int n) { int min = n % 10; int max = n % 10; while (n > 0) { int digit = n % 10; n = n / 10; if (digit < min) { min = digit; } if (digit > max) { max = digit; } } return max - min; } private static int count, failCount; public static void main(String[] args) { for (int i = 0; i <= 3876254; i++) { test(i); if (failCount == 30) { break; } } if (failCount == 0) { System.out.println("passed all tests"); } else { System.out.println("failed " + failCount + " of " + count + " tests"); } } public static void test(int n) { count++; int result2 = digitRange2(n); String exception = null; int result1 = 0; boolean fail = false; try { result1 = digitRange(n); } catch (RuntimeException e) { int line = e.getStackTrace()[1].getLineNumber(); exception = "threw " + e + " at line #" + line; fail = true; } if (!fail && result1 != result2) { fail = true; } if (fail) { System.out.println("failed for " + n); System.out.println("expected = " + result2); System.out.println("theirs = " + result1); if (exception != null) { System.out.println(exception); } System.out.println(); failCount++; } } }