Links

ΜΆ
Adam I. Gerard
TBD
TBD
TBD

Hexadecimal

Just your standard hexadecimal conversion.

  • Difficulty: Easy
  • Kind: Recursion
  • Platform: Technical Interview
  • Solved: N/A
  • Time Complexity: O(N)
  • Space Complexity: O(N)
  • Answer Rank: Top N/A

Insights

Hexadecimals represent number values using base 16. To convert a number into hexadecimal form involves recursively dividing the number by 16 and calculating any remainder. The remainder is used to calculate the symbol at each step. These values are passed to the next recurse call.
// 0-9
// A-F represent 10-15
var NUMS = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"];

function decimalToHexidecimal(num, remainders = []) {
  var r = num % 16,d = Math.floor(num / 16);
  print_console(`Remainder: ${r}`);
  print_console(`Long Division: ${d}`);

  remainders.push(NUMS[r]);
  if (d < 1) return remainders.reverse().join("");
  return decimalToHexidecimal(d, remainders);
}

function hexToDecimal(hex) {
  var num = 0,order = hex.length;

  for (var i = 0; i < hex.length; i++) {
    order--;
    var n = NUMS.indexOf(hex.charAt(i));
    num += n * Math.pow(16, order);
  }

  return num;
}

window.onload = function() {
  print_console(decimalToHexidecimal(100));
  print_console(decimalToHexidecimal(1000));
  print_console(hexToDecimal("64"));
  print_console(hexToDecimal("3E8"));
};

Test Cases

      Links