字符串相加问题
查看原帖
字符串相加问题
710834
cmyhhxx楼主2022/4/8 20:48

关于c++ string相加的问题

  • res += ito(to_decimal % p2) 全WA
  • res = ito(to_decimal % p2) + res AC

AC代码如下:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
#include <unordered_map>
#include <cmath>
#include <vector>

using namespace std;

typedef long long LL;
typedef pair<int, int> PII;

int oti(char a)
{
	if (a == 'A') return 10;
	if (a == 'B') return 11;
	if (a == 'C') return 12;
	if (a == 'D') return 13;
	if (a == 'E') return 14;
	if (a == 'F') return 15;
	return int (a - '0');
}

char ito(int a)
{
	if (a == 10) return 'A';
	if (a == 11) return 'B';
	if (a == 12) return 'C';
	if (a == 13) return 'D';
	if (a == 14) return 'E';
	if (a == 15) return 'F';
	return char (a + '0');	
}

int main()
{
	int p1, p2;
	string s;
	cin >> p1 >> s >> p2;
	
	int to_decimal = 0;
	int base = 1;
	
	
	for (int i = s.size() - 1; i >= 0; i -- )
	{
		to_decimal += base * oti(s[i]);
		base *= p1;
	}
	
	string res;
	
	while (to_decimal)
	{
		res =ito(to_decimal % p2) + res;
		to_decimal /= p2; 
	}
	
	cout << res << endl;
	
	return 0;
}


2022/4/8 20:48
加载中...