## The challenge

Convert an `integer` which is base 10, to a `hexadecimal` base 16 `string`.

Java provides various built-in options such as `Integer.toString(a, 16)`, or `String.format("0x%X", a)`, or `Integer.toHexString(a)`

## The solution in Java code

Option 1:

 ``````1 2 3 4 5 `````` ``````public class Hexadecimal{ public static String convertToHex(int a){ return "0x"+Integer.toHexString(a).toUpperCase(); } } ``````

Option 2:

 `````` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 `````` ``````public class Hexadecimal{ private static final String hexDigits = "0123456789ABCDEF"; public static String convertToHex(int a) { String hexadecimal = ""; while (a > 0) { int digit = a % 16; hexadecimal = hexDigits.charAt(digit) + hexadecimal; a = a / 16; } return "0x" + hexadecimal; } } ``````

Option 3:

 `````` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 `````` ``````public class Hexadecimal{ private static final String HEX = "0123456789ABCDEF"; public static String convertToHex(int a){ final StringBuilder sb = new StringBuilder(""); while (a != 0) { sb.append(HEX.charAt((a & 0xf))); a = a >> 4; } return "0x" + sb.reverse().toString(); } } ``````

Option 4:

 ``````1 2 3 4 5 6 7 8 `````` ``````public class Hexadecimal { private static final char[] numbers = {'0' , '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; public static String convertToHex(int a) { if (a < 16) return "0x" + numbers[a]; return convertToHex(a/16) + numbers[a%16]; } } ``````

## Test cases to validate our solution

 ``````1 2 3 4 5 6 7 8 9 `````` ``````import org.junit.Test; import static org.junit.Assert.assertEquals; public class HexadecimalShould { @Test public void test (){ assertEquals("0x100",Hexadecimal.convertToHex(256)); } } ``````

 `````` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 `````` ``````import org.junit.Test; import java.util.HashMap; import static org.junit.Assert.assertEquals; public class HexadecimalShould { @Test public void test (){ assertEquals("0x100",Hexadecimal.convertToHex(256)); int numbers[] = new int[1000]; for (int i = 0; i < numbers.length; i++) { numbers[i] = (int)Math.floor(Math.random()*4294967295.); assertEquals((new Hex()).convertToHex(numbers[i]),Hexadecimal.convertToHex(numbers[i])); } } private class Hex { public String convertToHex(int a) { String num = ""; HashMap mapeo = new HashMap<>(); for (int i = 0; i < 10; i++) mapeo.put(i + "", i + ""); mapeo.put("10", "A"); mapeo.put("11", "B"); mapeo.put("12", "C"); mapeo.put("13", "D"); mapeo.put("14", "E"); mapeo.put("15", "F"); while (a >= 16) { num += mapeo.get(a % 16 + "") + ""; a /= 16; } num += mapeo.get(a + ""); return "0x"+(new StringBuilder(num)).reverse().toString(); } } } ``````