Int to Hexadecimal
Given an integer, convert it to a hexadecimal representation.
Advanced
Instructions
Write a function that takes an integer as input and returns its hexadecimal representation.
For example, if the input is 26, the output should be "1a".
You can assume that the input integer is non-negative.
Tests
0/4
Function Call:
Expected:
intToHex(4)
"4"
Run test
intToHex(26)
"1a"
Run test
Hidden Test
?
Run test
Hidden Test
?
Run test
See Solution
Solution
Loping through the number
Basic idea
- We can convert a number to hexadecimal by repeatedly dividing the number by 16 and keeping track of the remainders.
- For negative numbers, we can use two's complement representation to convert them to positive numbers before converting them to hexadecimal.
const intToHex = (myInt) => {
if (myInt === 0) return "0";
if (myInt < 0) {
myInt = 0xFFFFFFFF + myInt + 1;
}
let hex = "";
while (myInt > 0) {
const remainder = myInt % 16;
hex = (remainder < 10 ? remainder : String.fromCharCode(remainder + 87)) + hex;
myInt = Math.floor(myInt / 16);
}
return hex;
}
Algorithm Detailed Explanation
- If the input number is 0, return "0".
- If the input number is negative, convert it to a positive number using two's complement representation.
- Initialize an empty string
hex
to store the hexadecimal representation of the number. - While the input number is greater than 0, do the following:
- Calculate the remainder when the number is divided by 16.
- If the remainder is less than 10, append it to the
hex
string. - If the remainder is greater than or equal to 10, convert it to the corresponding hexadecimal character and append it to the
hex
string. - Update the input number by dividing it by 16 (integer division).
- Return the
hex
string as the hexadecimal representation of the input number.
Complexity Analysis
- The time complexity of this solution is O(log(n)), where n is the input number.
- The space complexity is O(log(n)) as well, due to the space used to store the hexadecimal representation.
Built-in Method
const intToHex = (myInt) => {
return myInt.toString(16);
}
Basic idea
- JavaScript provides a built-in method
toString
that can be used to convert a number to a string in a specified base. - We can use this method with a base of 16 to convert a number to its hexadecimal representation.
Complexity Analysis
- The time complexity of this solution is O(1) since it uses a built-in method.
- The space complexity is O(1) as well.
Any improvement idea? Share with us!