用a-z来表示26进制数相加。
思想很简单,用一个string 来存储 a-z的数,,,用下标来进行26进制间的计算,,用内容来进行显示
#include <iostream>
#include <algorithm> //实现逆序
using namespace std;
int main()
{
/*
*
* */
string math26="abcdefghijklmnopqrstuvwxyz";
string first,second,third;
cout<<"*****实现两个26进制的数相加*****"<<endl;
cout<<"请输入第一个数(a~z): ";
cin>>first;
int firstLength=first.length();
for(int i=0;i<firstLength;i++)
{ if(first[i]<97 || first[i]>122)
{
cout<<"输入有误,请输入小写字母a~z的数";
return -1;
}
}
cout<<"请输入第二个数(a~z): ";
cin>>second;
int secondLength=second.length();
for(int i=0;i<secondLength;i++)
{ if(second[i]<97 || second[i]>122)
{
cout<<"输入有误,请输入小写字母a~z的数";
return -1;
}
}
reverse(first.begin(), first.end()) ; //倒序存储,使其方便相加减
reverse(second.begin(), second.end()) ;
/* 此部分的目的是为了使得两者的位数相等,方便我们进行运算
* 如果其中一者的位数少,则在其高位补‘a’
* */
int length=first.length();
if(firstLength<secondLength)
{
length=secondLength;
for( int i=firstLength;i<secondLength;i++)
first[i]='a';
}
else
{
for( int i=secondLength;i<firstLength;i++)
second[i]='a';
}
int compare=0,carry=0; //cary代表着是进位
for(int i=0;i<length;i++)
{
compare=(first[i]-97)+(second[i]-97)+carry;
if(compare<26)
{
third[i]=math26[compare];
carry=0;
}
else
{
third[i]=math26[compare-26] ;
carry =1;
}
}
if(carry==1) //如果两者相加在最后还多出来了一个进位
third[length]='b';
cout<<"两者相加的和为:";
for(int i=length;i>=0;i--)
cout<<third[i];
return 0;
}