Open In App

Given two hexadecimal numbers, write a Python program to compute their sum.

Examples:

```Input: a = "01B", b = "378"
Output: 393
Explanation: B (11 in decimal) + 8 = 19 (13 in hex), hence addition bit = 3,
carry = 1 1 + 7 + 1 (carry) = 9, hence addition bit = 9,
carry = 0 0 + 3 + 0 (carry) = 3, hence addition bit = 3,
carry = 0 01B + 378 = 393 ```
```Input: a = "AD", b = "1B"
Output: C8
Explanation: D(13 in Dec) + B(11 in Dec) = 24(18 in hex),
hence addition bit = 8, carry = 1 A(10 in Dec) + 1 + 1 (carry)= 12 (C in hex),
addition bit = C carry = 0 AD + 1B = C8```

Approach:

To add two hexadecimal values in python we will first convert them into decimal values then add them and then finally again convert them to a hexadecimal value. To convert the numbers we will make use of the hex() function The hex() function is one of the built-in functions in Python3, which is used to convert an integer number into its corresponding hexadecimal form. We will also use the int() function to convert the number to decimal form. The int() function in Python and Python3 converts a number in the given base to decimal.

Below are the implementations based on the above approach:

Method 1:

## Python3

 `# Python program to add two hexadecimal numbers.` `# Driver code``# Declaring the variables``a ``=` `"01B"``b ``=` `"378"` `# Calculating hexadecimal value using function``sum` `=` `hex``(``int``(a, ``16``) ``+` `int``(b, ``16``))` `# Printing result``print``(``sum``[``2``:])`

Output

`393`

Method 2:

## Python3

 `# Python program to add two hexadecimal numbers.` `# Driver code``# Declaring the variables``a ``=` `"B"``b ``=` `"C"` `# Calculating hexadecimal value using function``sum` `=` `hex``(``int``(a, ``16``) ``+` `int``(b, ``16``))` `# Printing result``print``(``sum``[``2``:])`

Output

`17`

Method 3:

## Python3

 `# Python program to add two hexadecimal numbers.` `# Driver code``if` `__name__ ``=``=` `"__main__"` `:` `    ``# Declaring the variables``    ``a ``=` `"01B"``    ``b ``=` `"378"``    ` `    ``# Calculating hexadecimal sum by using hex() and int()``    ``hexadecimal_sum ``=` `lambda` `a,b : ``hex``(``int``(a, ``16``) ``+` `int``(b, ``16``))``    ` `    ``# calling hexadecimal_sum lambda function``    ``print``(hexadecimal_sum(a,b)[``2``:])`

Output

`393`

Time complexity: O(1)
Space complexity: O(1)

## Python3

 `from` `operator ``import``*``num1``=``"01B"``num2``=``"378"``print``(``hex``(add(``int``(num1,``16``),``int``(num2,``16``))))`

Output

`0x393`

Time complexity: O(1)

Space complexity: O(1)

Method 5: Using manual addition of hexadecimal digits: This approach performs the addition manually by adding the digits of the two hexadecimal strings from right to left and carrying over as necessary. It also takes care of adding leading zeroes to make the two strings of equal length.

Steps:

1. Get two hexadecimal numbers as input strings.
2. Make the two input strings of equal length by adding leading zeroes.
3. Initialize carry as 0 and an empty string as the result.
4. For each position from right to left:
• Convert the two digits at that position to integers using the int() function.
• Add the two integers and the carry, and compute the sum and the new carry.
• Convert the sum to a hexadecimal digit using the hex() function and append it to the result string.
5. If there is a carry after the last addition, convert it to a hexadecimal digit and prepend it to the result string.
6. Return the result string as the sum of the two hexadecimal numbers.

## Python3

 `# Python program for the above approach` `# Function to add the two hexadecimal``# numbers a and b``def` `add_hexadecimal(a, b):``  ` `    ``# Make the two strings of equal length``    ``# by adding leading zeroes``    ``n ``=` `max``(``len``(a), ``len``(b))``    ``a ``=` `a.zfill(n)``    ``b ``=` `b.zfill(n)``    ` `    ``# Add the digits of the two strings``    ``# and carry over as necessary``    ``carry ``=` `0``    ``result ``=` `""``    ` `    ``for` `i ``in` `range``(n``-``1``, ``-``1``, ``-``1``):``        ``digit_sum ``=` `int``(a[i], ``16``) ``+` `int``(b[i], ``16``) ``+` `carry``        ``digit ``=` `hex``(digit_sum ``%` `16``)[``2``:]``        ``carry ``=` `digit_sum ``/``/` `16``        ``result ``=` `digit ``+` `result``    ``if` `carry:``        ``result ``=` `hex``(carry)[``2``:] ``+` `result``        ` `    ``# Return the result``    ``return` `result` `# Driver Code` `a ``=` `"01B"``b ``=` `"378"` `print``(add_hexadecimal(a, b))`

Output

`393`

Time Complexity: The time complexity of this approach is O(n), where n is the length of the longer hexadecimal string. This is because we have to iterate over each digit of the two strings once to add them together.

Space Complexity: The space complexity of this approach is O(n), where n is the length of the longer hexadecimal string. This is because we are creating a new string of length n to hold the sum of the two strings.

Method 6: Using reduce():

Algorithm:

1. Import the reduce() function from the functools module.
2. Define a function add_hex that takes two hexadecimal strings a and b as input.
3. Use a list comprehension to convert the input strings to a list of decimal integers.
4. Use the reduce() method to sum the list of decimal integers element-wise.
5. Convert the resulting decimal sum to a hexadecimal string using the built-in hex() function.
6. Use slicing to remove the “0x” prefix from the output string.
7. Return the resulting hexadecimal string.
8. Call the add_hex() function with sample input values “B” and “C”.
9. Print the output of the function call, which should be the sum of the two input values in hexadecimal format.

## Python3

 `from` `functools ``import` `reduce` `def` `add_hex(a, b):``    ``# convert hex strings to decimal integers and add them``    ``decimal_sum ``=` `reduce``(``lambda` `x, y: x ``+` `y, [``int``(x, ``16``) ``for` `x ``in` `[a, b]])``    ``# convert decimal sum to hex string and return it``    ``return` `hex``(decimal_sum)[``2``:]` `# test the function``a ``=` `"B"``b ``=` `"C"``print``(add_hex(a, b)) ``#This code is contributed by Jyothi pinjala.`

Output

`17`

The time complexity : O(n), where n is the number of input hexadecimal digits. This is because the list comprehension iterates over the input strings once, and the reduce() method also iterates over the resulting list of decimal integers once.

The space complexity : O(n), because the list comprehension creates a new list of decimal integers that is the same size as the input strings, and the reduce() method also creates a temporary variable to store the accumulated sum. However, since the size of the input strings is typically small, the space complexity of this implementation is not a concern.