题目
设有一个字符串S的结构为: n
其中为n数字串(长度<20),且2≤ p1, p2 ≤10。
程序要求:将p1进制的n按p2进制输出
例如:S="10<2>10"
其意义为:将二进制的102,输出为十进制的210。输出结果为:10<2>=2<10>
输入格式:
输入一行,仅有数字字符0~9与<、>组成,且格式严格符合 n
输出格式:
输出一行,格式为: n1
输入样例:
7<10>2
输出样例:
7<10>=111<2>
解题思路
7<10>=111<2>解题思路
数值范围很大,超过了 long long,所以要用unsigned long long 去存储,输入时也要使用string输入
str.c_str()的作用
//c_str():生成一个const char*指针,指向以空字符终止的数组。
在c语言中没有string类型,故必须通过string类对象的成员函数c_str()把string 对象转换成c中的字符串样式。
#includeusing namespace std; typedef unsigned long long ull; // 将p进制的字符串转成10进制的unsigned long long ull stoUll(const string &s, const int &p) { ull num = 0; ull pow = 1; for (int i = s.size() - 1; i >= 0; --i) { num += pow * (s[i] - '0'); pow *= p; } return num; } // 将10进制的unsigned long long数字转成p进制的字符串 string ullToString(ull num, const int &p) { string res; while (num != 0) { res = char('0' + (num % p)) + res; num /= p; } return res; } int main() { string s; cin >> s; int index1 = s.find('<'), index2 = s.find('>'); string n = s.substr(0, index1); int p1 = stoi(s.substr(index1 + 1, index2 - index1 - 1)); int p2 = stoi(s.substr(index2 + 1)); ull num = stoUll(n, p1); string res = ullToString(num, p2); printf("%s<%d>=%s<%d>n", n.c_str(), p1, res.c_str(), p2); return 0; }



