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:
public class Hexadecimal{ public static String convertToHex(int a){ return "0x"+Integer.toHexString(a).toUpperCase(); } }
Option 2:
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:
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:
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
import org.junit.Test; import static org.junit.Assert.assertEquals; public class HexadecimalShould { @Test public void test (){ assertEquals("0x100",Hexadecimal.convertToHex(256)); } }
Additional test cases
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<String, String> 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(); } } }