Given two numeric Hexadecimal numbers str1 and str2, the task is to add the two hexadecimal numbers.
Hexadecimal Number system, often shortened to “hex”, is a number system made up from 16 symbols. it uses 10 symbols from decimal number system which are represented by 0-9 and six extra symbols A – F which represent decimal 10 – 15.
Input: str1 = “01B”, str2 = “378”
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: str1 = “AD”, str2 = “1B”
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: The idea is to use a map template to store the mapped values that are hexadecimal to decimal and decimal to hexadecimal.
- Iterate until one of the given string reaches its length.
- Start with carrying zero and add both numbers(with the carry) from the end and update carry in each addition.
- Perform the same operation on the remaining length of the other string (if both the strings have different lengths).
- Return the value that has been added.
Below is the implementation of the above approach:
Time Complexity: O(max(N, M)), where the length of the string first and second is N and M.
Auxiliary Space: O(max(N, M)), where the length of the string first and second is N and M.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find the count of natural Hexadecimal numbers of size N
- Check the divisibility of Hexadecimal numbers
- Largest Even and Odd N-digit numbers in Hexadecimal Number System
- Largest and Smallest N-digit Hexadecimal Numbers
- Add two numbers represented by two arrays
- Convert a binary number to hexadecimal number
- Program for decimal to hexadecimal conversion
- Program for Hexadecimal to Decimal
- StringStream in C++ for Decimal to Hexadecimal and back
- Convert Hexadecimal value String to ASCII value String
- Convert a string to hexadecimal ASCII values
- Program to Convert Hexadecimal Number to Binary
- Program to Convert Hexadecimal to Octal
- Count Hexadecimal Number
- Reverse bytes of a Hexadecimal Number
- Check if a HexaDecimal number is Even or Odd
- How to validate Hexadecimal Color Code using Regular Expression
- Program to Convert Octal to Hexadecimal
- Hexadecimal equivalents in Binary Valued Graph
- Check if a string represents a hexadecimal number or not
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.