DDSA Solutions

405. Convert a Number to Hexadecimal

Time: O(1)
Space: O(1)
Advertisement

Intuition

For negative numbers, use two's complement (treat as unsigned 32-bit). Process 4 bits at a time (one hex digit) by AND-ing with 0xF and right-shifting. For two's complement in C#, cast to uint first.

Algorithm

  1. 1If num == 0, return "0".
  2. 2Use uint n = (uint)num to handle negatives as 32-bit unsigned.
  3. 3While n != 0: digit = n & 0xF. Prepend "0123456789abcdef"[digit] to result. n >>= 4.
  4. 4Return result.

Example Walkthrough

Input: num = 26

  1. 1.26 & 0xF = 10 -> "a". 26>>4 = 1. 1 & 0xF = 1 -> "1". Result = "1a".

Output: "1a"

Common Pitfalls

  • Cast to uint before processing to correctly handle negative numbers via two's complement.
405.cs
C#
// Approach: Extract each 4-bit nibble from bits 28 down to 0, map to hex
// character, skipping leading zeros. Handles negative numbers via two's complement.
// Time: O(1) Space: O(1)

public class Solution
{
    public string ToHex(int number)
    {
        if (number == 0)
            return "0";

        System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
        for (int index = 7; index >= 0; --index)
        {
            int hexDigit = (number >> (4 * index)) & 0xf;
            if (stringBuilder.Length > 0 || hexDigit != 0)
            {
                char character = hexDigit < 10 ? (char)(hexDigit + '0') : (char)(hexDigit - 10 + 'a');
                stringBuilder.Append(character);
            }
        }
        return stringBuilder.ToString();
    }
}
Advertisement
Was this solution helpful?