diff --git a/Conversions/DecimalToHexadecimal.js b/Conversions/DecimalToHexadecimal.js new file mode 100644 index 0000000000..5780bfa025 --- /dev/null +++ b/Conversions/DecimalToHexadecimal.js @@ -0,0 +1,28 @@ +/** + * @function decimalToHexadecimal + * @description Converts a decimal number (base-10) to its hexadecimal + * (base-16) string representation without using JavaScript's + * built-in toString(16). + * @param {number} decimal - A non-negative integer + * @returns {string} - The hexadecimal string representation in uppercase + * @see https://en.wikipedia.org/wiki/Hexadecimal + * @example decimalToHexadecimal(255) => "FF" + * @example decimalToHexadecimal(16) => "10" + * @example decimalToHexadecimal(0) => "0" + */ +const decimalToHexadecimal = (decimal) => { + if (!Number.isInteger(decimal) || decimal < 0) { + throw new TypeError('Input must be a non-negative integer') + } + if (decimal === 0) return '0' + const hexChars = '0123456789ABCDEF' + let hex = '' + let num = decimal + while (num > 0) { + hex = hexChars[num % 16] + hex + num = Math.floor(num / 16) + } + return hex +} + +export { decimalToHexadecimal } diff --git a/Conversions/test/DecimalToHexadecimal.test.js b/Conversions/test/DecimalToHexadecimal.test.js new file mode 100644 index 0000000000..b2a56b02b3 --- /dev/null +++ b/Conversions/test/DecimalToHexadecimal.test.js @@ -0,0 +1,43 @@ +import { decimalToHexadecimal } from '../DecimalToHexadecimal.js' + +describe('decimalToHexadecimal', () => { + test("decimalToHexadecimal(0) returns '0'", () => { + expect(decimalToHexadecimal(0)).toBe('0') + }) + + test("decimalToHexadecimal(10) returns 'A'", () => { + expect(decimalToHexadecimal(10)).toBe('A') + }) + + test("decimalToHexadecimal(15) returns 'F'", () => { + expect(decimalToHexadecimal(15)).toBe('F') + }) + + test("decimalToHexadecimal(16) returns '10'", () => { + expect(decimalToHexadecimal(16)).toBe('10') + }) + + test("decimalToHexadecimal(255) returns 'FF'", () => { + expect(decimalToHexadecimal(255)).toBe('FF') + }) + + test("decimalToHexadecimal(256) returns '100'", () => { + expect(decimalToHexadecimal(256)).toBe('100') + }) + + test("decimalToHexadecimal(4096) returns '1000'", () => { + expect(decimalToHexadecimal(4096)).toBe('1000') + }) + + test('throws TypeError for negative input', () => { + expect(() => decimalToHexadecimal(-1)).toThrow(TypeError) + }) + + test('throws TypeError for float input', () => { + expect(() => decimalToHexadecimal(1.5)).toThrow(TypeError) + }) + + test('throws TypeError for non-number input', () => { + expect(() => decimalToHexadecimal('FF')).toThrow(TypeError) + }) +})