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.
Examples:
Input: str1 = “01B”, str2 = “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 = 393Input: str1 = “AD”, str2 = “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
Approaches:
- Using a map template to find and store the values.
- Using inbuilt functions to find the sum.
Method 1: Using maps
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:
// C++ program for the above approach #include <bits/stdc++.h> using namespace std;
// Map for converting hexadecimal // values to decimal map< char , int > hex_value_of_dec( void )
{ // Map the values to decimal values
map< char , int > m{ { '0' , 0 }, { '1' , 1 },
{ '2' , 2 }, { '3' , 3 },
{ '4' , 4 }, { '5' , 5 },
{ '6' , 6 }, { '7' , 7 },
{ '8' , 8 }, { '9' , 9 },
{ 'A' , 10 }, { 'B' , 11 },
{ 'C' , 12 }, { 'D' , 13 },
{ 'E' , 14 }, { 'F' , 15 } };
return m;
} // Map for converting decimal values // to hexadecimal map< int , char > dec_value_of_hex( void )
{ // Map the values to the
// hexadecimal values
map< int , char > m{ { 0, '0' }, { 1, '1' },
{ 2, '2' }, { 3, '3' },
{ 4, '4' }, { 5, '5' },
{ 6, '6' }, { 7, '7' },
{ 8, '8' }, { 9, '9' },
{ 10, 'A' }, { 11, 'B' },
{ 12, 'C' }, { 13, 'D' },
{ 14, 'E' }, { 15, 'F' } };
return m;
} // Function to add the two hexadecimal numbers string Add_Hex(string a, string b) { map< char , int > m = hex_value_of_dec();
map< int , char > k = dec_value_of_hex();
// Check if length of string first is
// greater than or equal to string second
if (a.length() < b.length())
swap(a, b);
// Store length of both strings
int l1 = a.length(), l2 = b.length();
string ans = "" ;
// Initialize carry as zero
int carry = 0, i, j;
// Traverse till second string
// get traversal completely
for (i = l1 - 1, j = l2 - 1;
j >= 0; i--, j--) {
// Decimal value of element at a[i]
// Decimal value of element at b[i]
int sum = m[a[i]] + m[b[j]] + carry;
// Hexadecimal value of sum%16
// to get addition bit
int addition_bit = k[sum % 16];
// Add addition_bit to answer
ans.push_back(addition_bit);
// Update carry
carry = sum / 16;
}
// Traverse remaining element
// of string a
while (i >= 0) {
// Decimal value of element
// at a[i]
int sum = m[a[i]] + carry;
// Hexadecimal value of sum%16
// to get addition bit
int addition_bit = k[sum % 16];
// Add addition_bit to answer
ans.push_back(addition_bit);
// Update carry
carry = sum / 16;
i--;
}
// Check if still carry remains
if (carry) {
ans.push_back(k[carry]);
}
// Reverse the final string
// for desired output
reverse(ans.begin(), ans.end());
// Return the answer
return ans;
} // Driver Code int main( void )
{ // Initialize the hexadecimal values
string str1 = "1B" , str2 = "AD" ;
// Function call
cout << Add_Hex(str1, str2) << endl;
} |
import java.util.HashMap;
import java.util.Map;
public class HexadecimalAddition {
// Map for converting hexadecimal values to decimal
public static Map<Character, Integer> hexValueOfDec() {
Map<Character, Integer> map = new HashMap<>();
map.put( '0' , 0 );
map.put( '1' , 1 );
map.put( '2' , 2 );
map.put( '3' , 3 );
map.put( '4' , 4 );
map.put( '5' , 5 );
map.put( '6' , 6 );
map.put( '7' , 7 );
map.put( '8' , 8 );
map.put( '9' , 9 );
map.put( 'A' , 10 );
map.put( 'B' , 11 );
map.put( 'C' , 12 );
map.put( 'D' , 13 );
map.put( 'E' , 14 );
map.put( 'F' , 15 );
return map;
}
// Map for converting decimal values to hexadecimal
public static Map<Integer, Character> decValueOfHex() {
Map<Integer, Character> map = new HashMap<>();
map.put( 0 , '0' );
map.put( 1 , '1' );
map.put( 2 , '2' );
map.put( 3 , '3' );
map.put( 4 , '4' );
map.put( 5 , '5' );
map.put( 6 , '6' );
map.put( 7 , '7' );
map.put( 8 , '8' );
map.put( 9 , '9' );
map.put( 10 , 'A' );
map.put( 11 , 'B' );
map.put( 12 , 'C' );
map.put( 13 , 'D' );
map.put( 14 , 'E' );
map.put( 15 , 'F' );
return map;
}
// Function to add two hexadecimal numbers
public static String addHex(String a, String b) {
Map<Character, Integer> hexToDec = hexValueOfDec();
Map<Integer, Character> decToHex = decValueOfHex();
// Check if the length of the first string is greater than or equal to the second
if (a.length() < b.length()) {
String temp = a;
a = b;
b = temp;
}
int l1 = a.length();
int l2 = b.length();
String result = "" ;
int carry = 0 ;
int i = l1 - 1 ;
int j = l2 - 1 ;
while (j >= 0 ) {
int sum = hexToDec.get(a.charAt(i)) + hexToDec.get(b.charAt(j)) + carry;
char additionBit = decToHex.get(sum % 16 );
result = additionBit + result;
carry = sum / 16 ;
i--;
j--;
}
while (i >= 0 ) {
int sum = hexToDec.get(a.charAt(i)) + carry;
char additionBit = decToHex.get(sum % 16 );
result = additionBit + result;
carry = sum / 16 ;
i--;
}
if (carry > 0 ) {
result = decToHex.get(carry) + result;
}
return result;
}
public static void main(String[] args) {
String str1 = "1B" ;
String str2 = "AD" ;
String result = addHex(str1, str2);
System.out.println(result);
}
} |
# Python equivalent of above code # Create maps to convert hexadecimal values to decimal and vice versa hex_value_of_dec = { '0' : 0 , '1' : 1 , '2' : 2 , '3' : 3 , '4' : 4 ,
'5' : 5 , '6' : 6 , '7' : 7 , '8' : 8 , '9' : 9 , 'A' :
10 , 'B' : 11 , 'C' : 12 , 'D' : 13 , 'E' : 14 , 'F' : 15 }
dec_value_of_hex = { 0 : '0' , 1 : '1' , 2 : '2' , 3 : '3' , 4 : '4' ,
5 : '5' , 6 : '6' , 7 : '7' , 8 : '8' , 9 : '9' ,
10 : 'A' , 11 : 'B' , 12 : 'C' , 13 : 'D' , 14 : 'E' , 15 : 'F' }
# Function to add the two hexadecimal numbers def Add_Hex(a, b):
# Check if length of string first is
# greater than or equal to string second
if len (a) < len (b):
a, b = b, a
# Store length of both strings
l1, l2 = len (a), len (b)
ans = ""
# Initialize carry as zero
carry = 0
i, j = l1 - 1 , l2 - 1
# Traverse till second string
# get traversal completely
while j > = 0 :
# Decimal value of element at a[i]
# Decimal value of element at b[i]
sum = hex_value_of_dec[a[i]] + hex_value_of_dec[b[j]] + carry
# Hexadecimal value of sum%16
# to get addition bit
addition_bit = dec_value_of_hex[ sum % 16 ]
# Add addition_bit to answer
ans + = addition_bit
# Update carry
carry = sum / / 16
i, j = i - 1 , j - 1
# Traverse remaining element
# of string a
while i > = 0 :
# Decimal value of element
# at a[i]
sum = hex_value_of_dec[a[i]] + carry
# Hexadecimal value of sum%16
# to get addition bit
addition_bit = dec_value_of_hex[ sum % 16 ]
# Add addition_bit to answer
ans + = addition_bit
# Update carry
carry = sum / / 16
i - = 1
# Check if still carry remains
if carry:
ans + = dec_value_of_hex[carry]
# Reverse the final string
# for desired output
ans = ans[:: - 1 ]
# Return the answer
return ans
# Driver Code if __name__ = = '__main__' :
# Initialize the hexadecimal values
str1, str2 = "1B" , "AD"
# Function call
print (Add_Hex(str1, str2))
|
using System;
using System.Collections.Generic;
class Program
{ // Map for converting hexadecimal
// values to decimal
static Dictionary< char , int > HexValueOfDec()
{
// Map the values to decimal values
Dictionary< char , int > map = new Dictionary< char , int >
{
{ '0' , 0 }, { '1' , 1 },
{ '2' , 2 }, { '3' , 3 },
{ '4' , 4 }, { '5' , 5 },
{ '6' , 6 }, { '7' , 7 },
{ '8' , 8 }, { '9' , 9 },
{ 'A' , 10 }, { 'B' , 11 },
{ 'C' , 12 }, { 'D' , 13 },
{ 'E' , 14 }, { 'F' , 15 }
};
return map;
}
// Map for converting decimal values
// to hexadecimal
static Dictionary< int , char > DecValueOfHex()
{
// Map the values to the
// hexadecimal values
Dictionary< int , char > map = new Dictionary< int , char >
{
{ 0, '0' }, { 1, '1' },
{ 2, '2' }, { 3, '3' },
{ 4, '4' }, { 5, '5' },
{ 6, '6' }, { 7, '7' },
{ 8, '8' }, { 9, '9' },
{ 10, 'A' }, { 11, 'B' },
{ 12, 'C' }, { 13, 'D' },
{ 14, 'E' }, { 15, 'F' }
};
return map;
}
// Function to add the two hexadecimal numbers
static string AddHex( string a, string b)
{
Dictionary< char , int > m = HexValueOfDec();
Dictionary< int , char > k = DecValueOfHex();
// Check if length of string first is
// greater than or equal to string second
if (a.Length < b.Length)
{
string temp = a;
a = b;
b = temp;
}
// Store length of both strings
int l1 = a.Length, l2 = b.Length;
string ans = "" ;
// Initialize carry as zero
int carry = 0, i, j;
// Traverse till second string
// get traversal completely
for (i = l1 - 1, j = l2 - 1; j >= 0; i--, j--)
{
// Decimal value of element at a[i]
// Decimal value of element at b[i]
int sum = m[a[i]] + m[b[j]] + carry;
// Hexadecimal value of sum % 16
// to get addition bit
char additionBit = k[sum % 16];
// Add additionBit to answer
ans = additionBit + ans;
// Update carry
carry = sum / 16;
}
// Traverse remaining element
// of string a
while (i >= 0)
{
// Decimal value of element
// at a[i]
int sum = m[a[i]] + carry;
// Hexadecimal value of sum % 16
// to get addition bit
char additionBit = k[sum % 16];
// Add additionBit to answer
ans = additionBit + ans;
// Update carry
carry = sum / 16;
i--;
}
// Check if still carry remains
if (carry != 0)
{
ans = k[carry] + ans;
}
return ans;
}
// Driver Code
static void Main( string [] args)
{
// Initialize the hexadecimal values
string str1 = "1B" , str2 = "AD" ;
// Function call
Console.WriteLine(AddHex(str1, str2));
}
} // This code is contributed by Dwaipayan Bandyopadhyay |
// Create maps to convert hexadecimal values to decimal and vice versa const hex_value_of_dec = { '0' : 0, '1' : 1, '2' : 2, '3' : 3, '4' : 4,
'5' : 5, '6' : 6, '7' : 7, '8' : 8, '9' : 9,
'A' : 10, 'B' : 11, 'C' : 12, 'D' : 13,
'E' : 14, 'F' : 15};
const dec_value_of_hex = {0: '0' , 1: '1' , 2: '2' , 3: '3' , 4: '4' ,
5: '5' , 6: '6' , 7: '7' , 8: '8' , 9: '9' ,
10: 'A' , 11: 'B' , 12: 'C' , 13: 'D' ,
14: 'E' , 15: 'F' };
// Function to add the two hexadecimal numbers function Add_Hex(a, b)
{ // Check if length of string first is
// greater than or equal to string second
if (a.length < b.length) {
[a, b] = [b, a];
}
// Store length of both strings
const l1 = a.length, l2 = b.length;
let ans = '' ;
// Initialize carry as zero
let carry = 0;
let i = l1 - 1, j = l2 - 1;
// Traverse till second string
// get traversal completely
while (j >= 0)
{
// Decimal value of element at a[i]
// Decimal value of element at b[i]
let sum = hex_value_of_dec[a[i]] + hex_value_of_dec[b[j]] + carry;
// Hexadecimal value of sum%16
// to get addition bit
let addition_bit = dec_value_of_hex[sum % 16];
// Add addition_bit to answer
ans += addition_bit;
// Update carry
carry = Math.floor(sum / 16);
i--, j--;
}
// Traverse remaining element
// of string a
while (i >= 0)
{
// Decimal value of element
// at a[i]
let sum = hex_value_of_dec[a[i]] + carry;
// Hexadecimal value of sum%16
// to get addition bit
let addition_bit = dec_value_of_hex[sum % 16];
// Add addition_bit to answer
ans += addition_bit;
// Update carry
carry = Math.floor(sum / 16);
i--;
}
// Check if still carry remains
if (carry) {
ans += dec_value_of_hex[carry];
}
// Reverse the final string
// for desired output
ans = ans.split( '' ).reverse().join( '' );
// Return the answer
return ans;
} // Driver Code // Initialize the hexadecimal values let str1 = "1B" , str2 = "AD" ;
// Function call console.log(Add_Hex(str1, str2)); |
C8
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.
Method 2: Using inbuilt functions
- In python, there are inbuilt functions like hex() to convert binary numbers to hexadecimal numbers.
- 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 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.
- 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 is the implementation of the above approach:
Example 1:
#include <iostream> #include <sstream> int main() {
// Declaring the variables
std::string str1 = "1B" ;
std::string str2 = "AD" ;
// Calculating hexadecimal value
std::stringstream ss;
ss << std::hex << std::stoi(str1, nullptr, 16) + std::stoi(str2, nullptr, 16);
std::string sum = ss.str();
// Printing result
std::cout << sum << std::endl;
return 0;
} |
public class HexadecimalAddition {
public static void main(String[] args) {
// Declaring the variables
String str1 = "1B" ;
String str2 = "AD" ;
// Calculating hexadecimal value
int sum = Integer.parseInt(str1, 16 ) + Integer.parseInt(str2, 16 );
// Converting the sum back to hexadecimal
String resultHex = Integer.toHexString(sum).toUpperCase();
// Printing result
System.out.println(resultHex);
}
} |
# Program to add two hexadecimal numbers. # Driver code # Declaring the variables str1 = "1B"
str2 = "AD"
# Calculating hexadecimal value using function sum = hex ( int (str1, 16 ) + int (str2, 16 ))
# Printing result print ( sum [ 2 :])
|
using System;
class Program {
static void Main()
{
// Declaring the variables
string str1 = "1B" ;
string str2 = "AD" ;
// Calculating hexadecimal value
int sum = Convert.ToInt32(str1, 16)
+ Convert.ToInt32(str2, 16);
string hexSum = sum.ToString(
"X" ); // Convert the sum back to hexadecimal
// Printing result
Console.WriteLine(hexSum);
}
} |
function GFG(str1, str2) {
// Convert hexadecimal strings to the decimal and calculate the sum
const sum = (parseInt(str1, 16) + parseInt(str2, 16)).toString(16);
return sum;
} // Main function function main() {
const str1 = "1B" ;
const str2 = "AD" ;
// Calculating hexadecimal value
const sum = GFG(str1, str2);
// Printing result
console.log(sum);
} // Execute the main function main(); |
c8
Time complexity: O(1)
Auxiliary space: O(1)
Example 2:
#include <iostream> #include <sstream> // Function to add two hexadecimal numbers std::string addHexadecimal( const std::string& a,
const std::string& b)
{ // Convert hexadecimal strings to integers
std::stringstream ss;
ss << std::hex << a;
unsigned long long int intA;
ss >> intA;
ss.clear();
ss << std::hex << b;
unsigned long long int intB;
ss >> intB;
// Calculate sum and convert it back to hexadecimal
unsigned long long int sum = intA + intB;
std::stringstream result;
result << std::hex << sum;
// Return the result as a string
return result.str();
} int main()
{ // Declaring the variables
std::string a = "01C" ;
std::string b = "378" ;
// Calculating hexadecimal sum
std::string hexadecimalSum = addHexadecimal(a, b);
// Print the result
std::cout << hexadecimalSum << std::endl;
return 0;
} |
import java.util.Scanner;
public class HexadecimalAddition {
// Function to add two hexadecimal numbers
public static String addHexadecimal(String a, String b) {
// Convert hexadecimal strings to integers
long intA = Long.parseLong(a, 16 );
long intB = Long.parseLong(b, 16 );
// Calculate sum and convert it back to hexadecimal
long sum = intA + intB;
return Long.toHexString(sum);
}
public static void main(String[] args) {
// Declaring the variables
String a = "01C" ;
String b = "378" ;
// Calculating hexadecimal sum
String hexadecimalSum = addHexadecimal(a, b);
System.out.println(hexadecimalSum);
}
} |
# Python program to add two hexadecimal numbers. # Driver code if __name__ = = "__main__" :
# Declaring the variables
a = "01C"
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 :])
# This code is contributed by AnkThon
|
using System;
class Program {
// Function to add two hexadecimal numbers
static string AddHexadecimal( string a, string b)
{
// Convert hexadecimal strings to integers
ulong intA = Convert.ToUInt64(a, 16);
ulong intB = Convert.ToUInt64(b, 16);
// Calculate sum and convert it back to hexadecimal
ulong sum = intA + intB;
string result = sum.ToString( "X" );
// Return the result as a string
return result;
}
static void Main()
{
// Declaring the variables
string a = "01C" ;
string b = "378" ;
// Calculating hexadecimal sum
string hexadecimalSum = AddHexadecimal(a, b);
// Print the result
Console.WriteLine(hexadecimalSum);
}
} |
// Javascript program for the above approach // Function to add two hexadecimal numbers function addHexadecimal(a, b) {
// Convert hexadecimal strings to integers
let intA = parseInt(a, 16);
let intB = parseInt(b, 16);
// Calculate sum and convert it back to hexadecimal
let sum = intA + intB;
let hexadecimalSum = sum.toString(16);
// Return the result as a string
return hexadecimalSum;
} // Driver code // Declaring the variables let a = "01C" ;
let b = "378" ;
// Calculating hexadecimal sum let hexadecimalSum = addHexadecimal(a, b); // Print the result console.log(hexadecimalSum); // This code is contributed by Susobhan Akhuli |
394
Time complexity: O(1)
Auxiliary space: O(1)