GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • LeetCodeJavascript.com
  • Star on GitHub

This view

  • Original page
  • New address

GeezerVison is showing leetcodejavascript.com — #1271 - Hexspeak - LeetCode JavaScript Solutions

Back to all solutions

#1271 - Hexspeak

Easy • View on LeetCode • View on GitHub
String Math

Problem Description

A decimal number can be converted to its Hexspeak representation by first converting it to an uppercase hexadecimal string, then replacing all occurrences of the digit '0' with the letter 'O', and the digit '1' with the letter 'I'. Such a representation is valid if and only if it consists only of the letters in the set {'A', 'B', 'C', 'D', 'E', 'F', 'I', 'O'}.

Given a string num representing a decimal integer n, return the Hexspeak representation of n if it is valid, otherwise return "ERROR".

Solution

/**
 * @param {string} num
 * @return {string}
 */
var toHexspeak = function(num) {
  const hex = BigInt(num).toString(16).toUpperCase();
  const validChars = new Set(['0', '1', 'A', 'B', 'C', 'D', 'E', 'F']);

  for (const char of hex) {
    if (!validChars.has(char)) {
      return 'ERROR';
    }
  }

  return hex.replace(/0/g, 'O').replace(/1/g, 'I');
};
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.