Intuition
Just use the transformation algorithm from decimal to hexadecimal
Approach
Simulation by doing the following:
- compute
remain = num % 16, addremainto the result (push_back) - update
num = (num - remainder) / 16 - repeat step 1 and step 2 until
numis 0
Notice that when num < 0, we need use its complement.
Complexity
Time complexity: the loop depends on the number of digits of
$$O(\log n)$$num.Space complexity:
$$ O(1) $$
Code
| |