In: Computer Science
#include <iostream>
#include <string>
using namespace std;
string plus_hex(string hex1, string hex2)
{
if (hex1.length() < hex2.length())
hex1.swap(hex2);
/*Strat algorithm*/
int length1, length2;
length1 = hex1.length();
length2 = hex2.length();
int flag = 0; // carry
int get1, get2;
int sum;
while (length1>0)
{
//get first number
if (hex1[length1 - 1] >= 'A')
get1 = hex1[length1 - 1] - 55;
else
get1 = hex1[length1 - 1] - '0';
//get second number
if (length2 > 0)
{
if (hex2[length2 - 1] >= 'A')
get2 = hex2[length2 - 1] - 55;
else
get2 = hex2[length2 - 1] - '0';
}
else
get2 = 0;
//get the sum
sum = get1 + get2 + flag;
if (sum >= 16)
{
int left = sum % 16;
if (left >= 10)
hex1[length1 - 1] = 'A' + left % 10;
else
hex1[length1 - 1] = '0' + left;
flag = 1;
}
else
{
if (sum >= 10)
hex1[length1 - 1] = 'A' + sum % 10;
else
hex1[length1 - 1] = '0' + sum;
flag = 0;
}
length1--;
length2--;
}
if (flag == 1)
return "1" + hex1;
else
return hex1;
/*End of algorithm*/
}
int main(void)
{
string hex1, hex2,hex3;
int len;
cout<<"Enter 1st hexadecimal number of 10 or
fewer hex digits"<<endl;
cout<<"Type q to stop the entry of the hex
digits"<<endl;
getline(cin,hex1,'q');
cout<<"Your 1st hexadecimal number
is"<<hex1<<endl;
cout<<"Enter 2nd hexadecimal number of 10 or
fewer hex digits"<<endl;
cout<<"Type q to stop the entry of the hex
digits"<<endl;
getline(cin,hex2,'q');
cout<<"Your 2nd hexadecimal number
is"<<hex2<<endl;
hex3=plus_hex(hex1, hex2);
cout<<"Addition of above two number
is"<<hex3<<endl;
len=hex3.length();
//cout<<len;
if(len>10)
cout<<"Addition
Overtflow";
return 0;
}
Output:
Thank you.