![]() |
VOOZH | about |
Given a Hexadecimal number as an input, the task is to convert that number to a Binary number.
Examples:
Input: Hexadecimal = 1AC5 Output: Binary = 0001101011000101 Explanation: Equivalent binary value of 1: 0001 Equivalent binary value of A: 1010 Equivalent binary value of C: 1100 Equivalent binary value of 5: 0101 Input: Hexadecimal = 5D1F Output: Binary = 0101110100011111
Approach: A hexadecimal number is a positional numeral system with a radix, or base, of 16 and uses sixteen distinct symbols.
A binary number is a number expressed in the base-2 binary numeral system, which uses only two symbols: which are 0 (zero) and 1 (one).
To convert HexaDecimal number to Binary, the binary equivalent of each digit of the HexaDecimal number is evaluated and combined at the end to get the equivalent binary number.
Below is the implementation of the above approach:
Equivalent Binary value is : 0001101011000101
Time Complexity: O(n)
Auxiliary Space: O(1)
Alternate Approach :
Equivalent Binary value is: 0001101011000101
Time Complexity: O(1)
Auxiliary Space: O(1)
1. The function first defines a dictionary called hex_to_bin_dict, which maps each hexadecimal digit to its binary representation. This is done using a series of key-value pairs in the format 'hex_digit': 'binary_digit'.
2. The input hexadecimal number is converted to uppercase using the upper() method to avoid issues with lowercase letters.
3. The function then creates an empty string called bin_num, which will be used to store the binary representation of the input hexadecimal number.
4. For each digit in the input hexadecimal number, the corresponding binary digit is retrieved from the hex_to_bin_dict dictionary using square bracket notation, and added to the bin_num string. This process is repeated for each digit in the input hexadecimal number.
Finally, the function returns the binary representation of the input hexadecimal number as a string.
0001101011000101
Time complexity: O(n)
Auxiliary space: O(n)