Java Coding Week #2

Robert Torok October 23, 2018
Java Coding Week #2

This week we continue our coding challenges series.

Convert Decimal to Hex

Hexadecimal representation of an integer value can be done by performing the following steps:

  • Carry out modulo division on the number by the base (which is 16 in this case). The result (remainder) will specify the hexadecimal character.
  • Divide the number by 16
  • If the result of the division is not 0, Jump to #1

There’s one more step left: You’ll need to reverse the characters.

public String convertDecToHex(int number) {
    String hexChars = "0123456789ABCDEF";
    StringBuffer sb = new StringBuffer();
    int i = 0;
    do {
        sb.append(hexChars.charAt(number % 16));
        number /= 16;
    } while (number > 0);
    return "0x" + sb.reverse().toString();
}

Result:

jshell> convertDecToHex(255)
$3 ==> "0xFF"

Count the Duplicates

Another simple task is count the individual characters in a word.

public void countDuplicates(String word) {
    if (word == null || word.isEmpty()) {
        return;
    }
    Map<Character, Integer> characterMap = new HashMap<>();
    for (int i = 0; i < word.length() - 1; i++) {
        Integer count = characterMap.get(word.charAt(i));
        if (count == null) {
            characterMap.put(word.charAt(i), 1);
        } else {
            characterMap.put(word.charAt(i), count + 1);
        }
    }
    for (Character c : characterMap.keySet()) {
        int cnt = characterMap.get(c);
        if (cnt > 1) {
            System.out.println(c + " " + characterMap.get(c));
        }
    }
}

Result:

jshell> countDuplicates("hello world")
l 3
o 2

Fibonacci Series

public int fibonacci(int n) {
    if (n == 0 || n == 1)
        return 1;
    return fibonacci(n - 1) + fibonacci(n - 2);
}

Result: