【笔试】n进转换

1：数字的字符串其中包括0-9和a-z(表示10-35)。
2：所有的输入和输出都只会是小写字母或数字，不存在其他字符。

#include <iostream>
#include <string>
#include <algorithm>
#include <math.h>
#include <vector>
using namespace std;
int main()
{
int n;
int iNum = 0;/////
string str1, str2;
while (cin >> n >> str1 >> str2)
{
if (n >= 2 && n <= 35)//////断言进制是否满足要求
{
int sumStr1 = 0;
int sumStr2 = 0;
string::iterator it1 = max_element(str1.begin(), str1.end());
string::iterator it2 = max_element(str2.begin(), str2.end());
reverse(str1.begin(), str1.end());
reverse(str2.begin(), str2.end());
vector<char>chVec;//存放n进制的每一位
if (n <= 10)
{
if (*it1 > '0' + n - 1 || *it2 > '0' + n - 1)
{
cout << -1 << endl;
return -1;
}
else
{
for (int i = 0; i < str1.size(); i++)
{
int n1 = str1[i] - '0';
sumStr1 += n1*pow((float)n, i);
}
for (int i = 0; i < str2.size(); i++)
{
int n1 = str2[i] - '0';
sumStr2 += n1*pow((float)n, i);
}
}
int sum = sumStr1 + sumStr2;
do
{
//iNum++;
chVec.push_back(sum%n+'0');
sum = sum / n;
} while (sum != 0);
reverse(chVec.begin(), chVec.end());
copy(chVec.begin(), chVec.end(), ostream_iterator<char>(cout, ""));
/*for (int i = 0; i < chVec.size(); i++)
{

cout << chVec[i];
}*/
cout << endl;
//cout << sumStr1 + sumStr2 << endl;
//return sumStr1+sumStr2;
}
else
{
if (*it1 > 86 + n || *it2 > 86 + n)
{
cout << -1 << endl;
return -1;
}
else
{
for (int i = 0; i < str1.size(); i++)
{
if (str1[i] >= '0' && str1[i] <= '9')
{
int n1 = str1[i] - '0';
sumStr1 += n1*n1*pow((float)n, i);
}
else
{
int n1 = str1[i] - 'a'+10;
sumStr1 += n1*pow((float)n, i);
}
}
for (int i = 0; i < str2.size(); i++)
{
if (str2[i] >= '0' && str2[i] <= '9')
{
int n1 = str2[i] - '0';
sumStr2 += n1*pow((float)n, i);
}
else
{
int n1 = str2[i] - 87;
sumStr2 += n1*pow((float)n, i);
}
}
}
int sum = sumStr1 + sumStr2;
//cout << sum << endl;
do
{
//iNum++;
if (sum%n >= 10)
chVec.push_back(sum%n-10+'a');
else
chVec.push_back(sum%n+'0');
sum = sum / n;
} while (sum != 0);
reverse(chVec.begin(),chVec.end());
copy(chVec.begin(),chVec.end(),ostream_iterator<char>(cout,""));

cout << endl;
//cout << sumStr1 + sumStr2 << endl;
//return sumStr1+sumStr2;
}
}
}
system("pause");
return 0;
}



• 本文已收录于以下专栏：

举报原因： 您举报文章：【笔试】n进转换 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)