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