fork download
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4.  
  5. // 字符转数字: '0'-'9' -> 0-9, 'A'-'Z' -> 10-35
  6. int charToNum(char c) {
  7. if (c >= '0' && c <= '9') return c - '0';
  8. return c - 'A' + 10;
  9. }
  10.  
  11. // 数字转字符
  12. char numToChar(int n) {
  13. if (n < 10) return '0' + n;
  14. return 'A' + n - 10;
  15. }
  16.  
  17. // 任意进制字符串转十进制
  18. long long toDecimal(const string& s, int base) {
  19. long long result = 0;
  20. for (char c : s)
  21. result = result * base + charToNum(c);
  22. return result;
  23. }
  24.  
  25. // 十进制转任意进制字符串
  26. string fromDecimal(long long n, int base) {
  27. if (n == 0) return "0";
  28. string result;
  29. while (n > 0) {
  30. result = numToChar(n % base) + result;
  31. n /= base;
  32. }
  33. return result;
  34. }
  35.  
  36. int main() {
  37. string s;
  38. int fromBase, toBase;
  39.  
  40. cout << "输入数字及原进制: ";
  41. cin >> s >> fromBase;
  42.  
  43. cout << "输入目标进制: ";
  44. cin >> toBase;
  45.  
  46. long long dec = toDecimal(s, fromBase);
  47. cout << s << " (" << fromBase << " 进制) = "
  48. << fromDecimal(dec, toBase) << " (" << toBase << " 进制)" << endl;
  49.  
  50. return 0;
  51. }
Success #stdin #stdout 0s 5316KB
stdin
Standard input is empty
stdout
输入数字及原进制: 输入目标进制:  (-780443384 进制) = 0 (5406 进制)