fork download
  1. import java.util.Scanner;
  2.  
  3. class PPROG_pl6_ex8 {
  4.  
  5. public static final Scanner input = new Scanner(System.in);
  6.  
  7. private static final int BASE = 16;
  8. private static final String[] HEX_DIGITS = "0123456789ABCDEF".split("");
  9.  
  10. public static void main(String[] args) {
  11. int num;
  12. do {
  13. num = askNum();
  14. System.out.println(num + " -> " + convertToHex(num));
  15. } while (num != 0);
  16. }
  17.  
  18. private static int askNum() {
  19. //System.out.println("Introduza o número");
  20. return Integer.parseInt(input.nextLine());
  21. }
  22.  
  23. public static String convertToHex(int num) {
  24. if (num == 0) return "0";
  25. boolean negativo = num < 0;
  26. if (negativo) num = -num;
  27. String resposta = "";
  28.  
  29. do {
  30. int alg = num % BASE;
  31. num /= BASE;
  32. String valueOfAlg = HEX_DIGITS[alg];
  33. resposta = valueOfAlg + resposta;
  34. } while (num != 0);
  35.  
  36. if (negativo) resposta = "-" + resposta;
  37. return resposta;
  38. }
  39. }
Success #stdin #stdout 0.06s 4386816KB
stdin
1
2
3
4
9
10
11
15
16
31
50
256
513
64876487
-1
-2
-15
-16
-255
-256
-47839
-3473732
0
stdout
1 -> 1
2 -> 2
3 -> 3
4 -> 4
9 -> 9
10 -> A
11 -> B
15 -> F
16 -> 10
31 -> 1F
50 -> 32
256 -> 100
513 -> 201
64876487 -> 3DDEFC7
-1 -> -1
-2 -> -2
-15 -> -F
-16 -> -10
-255 -> -FF
-256 -> -100
-47839 -> -BADF
-3473732 -> -350144
0 -> 0