在二十进制中,我们除了使用数字0-9以外,还使用字母a-j(表示10-19),给定两个二十进制整数,求它们的和。 输入是两个二十进制整数,且都大于0,不超过100位; 输出是它们的和(二十进制),且不包含首0。我们用字符串来表示二十进制整数。
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
class Test {
public:
static string calculate (string x,string y)
{
int lenX = x.length();
int lenY = y.length();
int numX[110] = {0,};
int numY[110] = {0,};
int pos = 0;
for (int i = lenX-1; i >= 0; i--)
{
if (x[i] <= '9' && x[i] >= '0')
{
numX[pos] = x[i] - '0';
}
else
{
numX[pos] = x[i] - 'a' + 10;
}
pos++;
}
pos = 0;
for (int i = lenY-1; i >= 0; i--)
{
if (y[i] <= '9' && y[i] >= '0')
{
numY[pos] = y[i] - '0';
}
else
{
numY[pos] = y[i] - 'a' + 10;
}
pos++;
}
int totalLen = lenX > lenY ? lenX : lenY;
string result = "";
int c = 0;
char temp = 0;
pos = 0;
while (pos < totalLen)
{
temp = numX[pos] + numY[pos] + c;
c = temp / 20;
temp %= 20;
if (temp <= 9)
{
result.insert(0, 1, temp+'0');
}
else
{
result.insert(0, 1, temp+'a'-10);
}
pos++;
}
if (c != 0)
{
result.insert(0, 1, '1');
}
return result;
}
};
//start 提示:自动阅卷起始唯一标识,请勿删除或增加。
int main()
{
cout<<Test::calculate("1234567890","1234567890")<<endl;
}
//end //提示:自动阅卷结束唯一标识,请勿删除或增加。