清华大学机试 进制转换2 Easy *注意进制溢出问题

基本思想:

第一次见到数据规模没有给出结果进制溢出;

 

原则上讲,如果多进制超过10进制,其余的数字用字母A-Z代替;

 

并且如果是高进制,也一定要注意,千万不要出现加和溢出的情况,这道题longlong才可以,int会存在溢出;

 

关键点:

无;

 

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<map>
using namespace std;

typedef long long ll;

int m, n;

string charge(string s) {
	//先转换成十进制;
	ll cnt = 0;
	for (int i = 0; i < s.size(); i++) {
		if (s[i] >= '0'&&s[i] <= '9') {
			cnt = cnt * m + (s[i] - '0');
		}
		else {
			cnt = cnt * m + (s[i] - 'A') + 10;
		}
	}
	//十进制转换为n进制数;
	string res = "";
	if (cnt == 0)
		return "0";
	while (cnt != 0) {
		if (cnt%n > 9) {
			//如果从10开始;
			res = char(cnt%n-10 + 'a') + res;
		}
		else {
			res = char(cnt%n + '0') + res;
		}
		cnt /= n;
	}
	return res;
}

int main() {
	string s;
	while (cin >> m >> n) {
		cin >> s;
		cout << charge(s) << endl;
	}
	return 0;
}

  

posted @ 2020-03-04 10:52  暮云林凌  阅读(171)  评论(0)    收藏  举报