pat甲級 1010 Radix (二分查找)

做題+看代碼2h...debug半小時

#include <iostream>
#include <cctype>
#include <algorithm>
#include <cmath>
#include<string>
using namespace std;
long long convert(string n, long long radix) {
	long long _n = 0;
	int temp=0, index = 0;
	for (auto c = n.rbegin(); c != n.rend(); c++) {
		temp = isdigit(*c) ? *c - '0' : *c - 'a' + 10;
		_n +=temp* pow( radix,index++);
	}
	return _n;
}
long long find_radix(string n,long long num) {
	char it = *max_element(n.begin(), n.end());
	long long low = (isdigit(it) ? it - '0': it - 'a' + 10) + 1;
	long long high = max(num, low);
	while (low <= high) {
		long long mid = (low + high) / 2;
		long long t = convert(n, mid);
		if (t<0||t > num)	high = mid - 1;
		else if (t == num)	return mid;
		else  low = mid + 1;
	}
	return -1;
}
int main() {
	string n1, n2;
	long long tag=0, radix=0, result_radix=0;
	cin >> n1 >> n2 >> tag >> radix;
	if (tag == 1)
		result_radix = find_radix(n2, convert(n1, radix));
	else
		result_radix = find_radix(n1, convert(n2, radix));
	if (result_radix != -1)
		cout << result_radix << endl;
	else
		cout << "Impossible\n";
	return 0;
	system("pause");
}

 

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