Tutorialspoint
Problem
Solution
Submissions

Convert a Decimal Number to Hexadecimal

Certification: Basic Level Accuracy: 51.39% Submissions: 144 Points: 5

Write a Python program that converts a decimal number to its hexadecimal representation.

Example 1
  • Input: 10
  • Output: "a"
  • Explanation:
    • Step 1: Take the input number 10.
    • Step 2: Convert 10 to its hexadecimal representation, which is "a".
    • Step 3: Return "a" as the result.
Example 2
  • Input: 255
  • Output: "ff"
  • Explanation:
    • Step 1: Take the input number 255.
    • Step 2: Convert 255 to its hexadecimal representation, which is "ff".
    • Step 3: Return "ff" as the result.
Constraints
  • 0 ≤ number ≤ 10^9
  • Return the hexadecimal representation as a lowercase string without the "0x" prefix
  • Time Complexity: O(log n), where n is the input number
  • Space Complexity: O(log n)
MapFunctions / MethodsRecursionGoogleShopify
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 hex() function: hex(number)[2:]
  • Use format(): format(number, 'x')
  • Create a hex digit mapping and use iterative division
  • Use recursion with hex mapping: def to_hex(n): return "" if n == 0 else to_hex(n // 16) + "0123456789abcdef"[n % 16]

The following are the steps to convert a decimal number to hexadecimal:

  • Take a decimal number as input.
  • Use `hex(num)[2:]` to get the hexadecimal representation.
  • Print the result.
  • Check with numbers like `255` (should give `FF`).

Submitted Code :