878733. Convert to Hexadecimal

Easy

Here is the detailed Markdown blog post for the problem "Convert to Hexadecimal":

Convert to Hexadecimal

Summary

The problem requires you to convert a given decimal number into its hexadecimal equivalent. This involves understanding the concept of base conversion, specifically from decimal (base 10) to hexadecimal (base 16).

Detailed Explanation

To solve this problem, we need to understand how to convert between different number bases. In this case, we'll be converting from decimal (base 10) to hexadecimal (base 16).

Here's a step-by-step breakdown of the solution:

  1. First, determine the remainder when the given decimal number is divided by 16. This will give you the hexadecimal value for that particular power of 16.

  2. Next, find out how many times you can divide the original number by 16 and get a quotient. This will tell you how many powers of 16 are needed to represent the original number in hexadecimal.

  3. Now, start from the right side of the hexadecimal representation and add each remainder (from step 1) as a new digit, moving leftward.

  4. Repeat steps 2-3 until all powers of 16 have been used up or the quotient becomes zero.

Time complexity: O(log n), where n is the given decimal number. Space complexity: O(1).

Optimized Solutions

C++

View on GeeksforGeeks
public class Main {
    public static String convertToHex(int decimal) {
        StringBuilder hex = new StringBuilder();
        while (decimal > 0) {
            int remainder = decimal % 16;
            if (remainder < 10)
                hex.insert(0, (char)(remainder + '0'));
            else
                hex.insert(0, (char)(remainder - 10 + 'A'));
            decimal /= 16;
        }
        return "0x" + hex.toString();
    }

    public static void main(String[] args) {
        int decimal = 12345;
        System.out.println(convertToHex(decimal));
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.