小明得到了一个数,但不确定这个数的进制,只知道可能是2~16进制的其中之一,所以她想请你帮忙算出所以可能的结果,并转成十进制后对pow(10, 9) 进行取模,把所得到的答案从小到大排列,若存在相同的结果,只保留一个即可。
输入描述:一个数,只会是‘0’-‘9‘ 和 ’A‘-’Z‘之间的字符。
例如输入11;
输出3,4,5,6,7,8,9,10,11,12,13,14,15,16,17。
#include < iostream >
#include < set >
#include < cmath >
#include < string >
#include < cctype >
using namespace std;
const long long yu = pow(10, 9) ; // 取余的数字
long long ntonum(string num, int i); //输入字符串num和进制i可以得到该进制对应的十进制数
int find_max(string s);//找到字符串中最大的字符,并返回成对应的数字,A->10
int strtonum(char s);//将字符串转成数字,方便存数据
int main(void)
{
string num ;
set<long long> out;
cout << "Enter a num: "; // input
cin >> num;
int max = find_max(num);
cout << max << endl;
if(max < 0)
{
cout << num << " is problem(not is 0-9 and A-Z.)\n" ;
return -1;
}
for(int i = max+1; i <= 16; ++i)
{
cout << "i = " << i << " num: ";
cout << ntonum(num, i) % yu << endl;
out.insert(ntonum(num, i) % yu ); // zi dong paixu er qie bu chong fu
}
return 0;
}
int find_max(string s)
{
if (!s.size()) // null
return 0;
int wei = s.size(); // 字符串位数
char ch = toupper(s[0]);
int temp = -1;
for (int i = 0; i < wei; ++i)
{
if('0' <= s[i] && s[i] <= '9') // 0-9
{
if(s[i] > ch)
ch = s[i];
temp = int(ch - '0');
}
else if('A' <= toupper(s[i]) && toupper(s[i]) <= 'Z') // A - Z
{
if(s[i] > ch)
ch = toupper(s[i]);
temp = int(ch-'A' + 10);
}
else
{
cout << s << " has not belong 0-9 and A - Z<find max> \n";
}
}
return temp; //返回最大位对应的数字
}
long long ntonum(string num, int i)
{
long long out = 0;
int k = num.size();
int a[k] = { 0 };
int multi = 1;
for(int j = k; j > 0; j--)
{
a[k-j] = strtonum(num[j-1]);//字符串对应的数字提取出来
}
for(int j = 0; j < k; j++)
{
out += a[j] * multi;
multi *= i;
}
return out; //返回十进制数
}
int strtonum(char s)
{
int temp = -1;
if('0' <= s && s <= '9')
{
temp = int(s - '0');
}
else if('A' <= s && s <= 'Z')
{
temp = int(s - 'A' + 10);
}
else
cout << s << " is not belong to 0-9 and A-Z.<strtonum>\n";
return temp;
}
本来想改进改进,让小写a-z也可以转,懒得动了。