PAT-甲級-1010-Radix

Practice 1010

PAT甲級1010
PAT甲級1010

My Solution

#include <cstdio>
#include <string>
#include <iostream>
#include <algorithm>
typedef long long LL;
using namespace std;

LL toArabicNumeral(char c) {
	if(c>= '0' && c<='9') {
		return c - '0';
	}
	return c - 'a' + 10;
}

LL toDecimalNumber(string str, LL radix) {
	LL decnum=0;
	LL rad=1;
	for(int i=str.size()-1; i>=0; i--, rad *= radix) {
		decnum += rad * toArabicNumeral(str[i]);
		if(decnum < 0 || rad < 0) {
			return -1;
		}
	}
	return decnum;
}

int main() {
	string N1, N2;
	int tag, radix;
	cin >> N1 >> N2 >> tag >> radix;
	
	if(tag==2) {
		swap(N1, N2);
	}
	
	LL decnum = toDecimalNumber(N1, radix);
	LL left=2, right=decnum;
	for(int i=0; i<N2.size(); i++) {
		left = max(left, toArabicNumeral(N2[i]) + 1);
	}
	
	LL mid, temp;
	while(right >= left) {
		mid = (left+right) >> 1;
		temp = toDecimalNumber(N2, mid);
		if(temp >= decnum || temp == -1) {
			right = mid-1;
		} else {
			left = mid+1;
		}
	}
	
	if(toDecimalNumber(N2, left) == decnum) {
		cout << left << endl;
	} else {
		cout << "Impossible" << endl;
	}
	
	return 0;
}

Test Result

PAT甲級1010
Any idea or discussion is highly welcomed.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章