Tutorialspoint
Problem
Solution
Submissions

Number to Hexadecimal

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a C# program to convert a given integer to its hexadecimal representation without using built-in methods like ToString("X"). For negative integers, use the two's complement method and output the result as a 32-bit representation.

Example 1
  • Input: num = 26
  • Output: "1a"
  • Explanation:
    • 26 in decimal equals 1a in hexadecimal.
Example 2
  • Input: num = -1
  • Output: "ffffffff"
  • Explanation:
    • -1 in two's complement 32-bit representation is all 1's, which in hexadecimal is "ffffffff".
Constraints
  • -2^31 ≤ num ≤ 2^31 - 1
  • Time Complexity: O(log n), where n is the input number
  • Space Complexity: O(1) not counting the output string
  • You cannot use built-in methods to directly convert the number to hexadecimal
Bitwise OperationsTech MahindraShopify
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use bitwise operations to extract 4 bits at a time.
  • Remember that hexadecimal uses characters 0-9 and a-f.
  • For negative numbers, use the two's complement representation.
  • Build the result string from right to left, then reverse it.

Steps to solve by this approach:

 Step 1: Handle the special case where the input number is 0, returning "0".
 Step 2: Create an array of hexadecimal characters (0-9, a-f) for lookup.
 Step 3: Initialize a StringBuilder to build the result.
 Step 4: While the number is not zero, extract the last 4 bits using the bitwise AND operation with 15 (which is 1111 in binary).
 Step 5: Convert the extracted 4 bits to their hexadecimal representation using the lookup array, and insert it at the beginning of the result.
 Step 6: Right shift the number by 4 bits to process the next group of 4 bits. Use unsigned right shift to handle negative numbers correctly.
 Step 7: Return the final string built by the StringBuilder.

Submitted Code :