Skip to content

Instantly share code, notes, and snippets.

@KevinTCoughlin
Last active January 10, 2016 23:36
Show Gist options
  • Select an option

  • Save KevinTCoughlin/9baf7822cfd7479eb3b8 to your computer and use it in GitHub Desktop.

Select an option

Save KevinTCoughlin/9baf7822cfd7479eb3b8 to your computer and use it in GitHub Desktop.
  • Example 1: Write a function to reverse a string.
    // Question #1
    public static String reverse(final String s) {
        final char[] chars = s.toCharArray();
        final int pivot = chars.length / 2;
        for (int i = 0; i < pivot; i++) {
            final int pos = chars.length - i - 1;
            final char c = chars[i];
            final char d = chars[pos];
            chars[i] = d;
            chars[pos] = c;
        }
        return String.valueOf(chars);
    }
  • Example 2: Write function to compute Nth fibonacci number:
    public static int fibonacci(final int n) {
        return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);
    }
  • Example 3: Print out the grade-school multiplication table up to 12x12
    public static void printMultiplicationTable(final int n) {
        for (int i = 1; i <= n; i++) {
            for (int k = 1; k <= n; k++) {
                System.out.print(String.format("%4d ", k * i));
            }
            System.out.println();
        }
    }
  • Example 4: Write a function that sums up integers from a text file, one int per line.
    public static int sumFile(final String path) throws FileNotFoundException {
        final File file = new File(path);
        final Scanner scanner = new Scanner(file);
        int sum = 0;
        while (scanner.hasNext()) {
            sum += Integer.parseInt(scanner.nextLine());
        }
        scanner.close();
        return sum;
    }
  • Example 5: Write function to print the odd numbers from 1 to 99.
    public static void printOdds(final int max) {
        for (int i = 1; i <= max; i += 2) {
            System.out.print(i + " ");
        }
    }
  • Example 6: Find the largest int value in an int array.
    public static int max(final int[] ints) {
        int max = ints[0];
        for (int i = 1; i < ints.length; i++) {
            if (max < ints[i]) {
                max = ints[i];
            }
        }
        return max;
    }
  • Example 7: Format an RGB value (three 1-byte numbers) as a 6-digit hexadecimal string.
    public static String rgbToHex(final int r, final int g, final int b) {
        return (toHex(r) + toHex(g) + toHex(b)).toUpperCase();
    }

    private static String toHex(final int i) {
        final String s = Integer.toHexString(i);
        return s.length() == 1 ? "0" + s : s;
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment