【笔试】n进转换

我是网络公司的一名普通程序员,英文名Steven,发音比较像“师弟”,自从入职培训自我介绍后,大家就称我为“二师弟”,我喜欢看科幻小说,也喜欢做梦,有一次梦到外星球,发现外星人使用的并非10进制/16进制等,有些星球居然使用N进制(据统计N都在2~35之间),现在我们将首先给您一个数字表示N进制,然后给出两个数字的字符串,请算出其求和结果并输出,如果输入不能正常计算则输出-1。
说明:
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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值