Convert a Number to Hexadecimal
Convert a Number to Hexadecimal
Bit Manipulation
Problem Statement
Given an integer num, write an algorithm to convert it to hexadecimal. For negative integers, two’s complement method is used.
Examples
Example 1:
Input: num = 26
Output: "1a"
Example 2:
Input: num = -1
Output: "ffffffff"
Solution (Bitwise Grouping)
We can convert the number by processing its bits in groups of 4, as each hexadecimal digit corresponds to exactly 4 bits (a nibble).
Algorithm Steps
- Handle the edge case: if the input is 0, return "0".
- Create a mapping from numbers 0-15 to their hex characters ('0'-'9', 'a'-'f').
- Initialize an empty result string.
- Iterate as long as the number is not zero and we haven't processed all 8 nibbles (for a 32-bit integer).
- Get the last 4 bits using a bitwise AND with 15 (which is 1111in binary):num & 15.
- Map this value to its hex character and prepend it to the result string.
- Right-shift the number by 4 bits to process the next nibble: num >>= 4.
- Return the result string.
Current Number (Binary)
00000000000000000000000000011010
Current Hex Result
""
Initial number: 26
Convert to Hex Solution