Problem Description
Little Rabbit is interested in radix. In a positional numeral system, the radix is the number of unique digits, including the digit 0, used to represent numbers. For example, for the decimal system (the most common system in use today) the radix is ten, because it uses the ten digits from 0 to 9. Generally, in a system with radix b (b>1), a string of digits d1…dn denotes the number d1bn−1+d2bn−2+⋯+dnb0, where 0≤di<b.
Little Rabbit casually writes down an equation. He wonders which radix this equation fits.
Input
The are several test cases. Each test case contains a string in a line, which represents the equation Little Rabbit writes down. The length of the string is at most 15. The input is terminated by the end-of-file.
The equation’s format: number, operator, number, =, number. There’s no whitespace in the string.
Each number has at least 1 digit, which may contain digital numbers 0 to 9 or uppercase letters A to F (which represent decimal 10 to 15). The number is guaranteed to be a non-negative integer, which means it doesn’t contain the radix point or negative sign. But the number may contain leading zeros.
The operator refers to one of +, −, ∗, or /. It is guaranteed that the number after / will not be equal to 0. Please note that the division here is not integer division, so 7/2=3 is not correct.
Output
For each test case, output an integer r (2≤r≤16) in a line, which means the equation is correct in the system with radix r. If there are multiple answers, output the minimum one. If there is no answer between 2 and 16, output −1.
Sample Input
1+1=10
18-9=9
AA*AA=70E4
7/2=3
Sample Output
2
10
16
-1
题意:以字符串的形式给出表达式,判断满足该表达式计算的最小进制。
思路:暴力模拟就行
代码:
#include<bits/stdc++.h>
#define ll long long
using namespace std;
bool check(string s, int n)
{
ll num1 = 0, num2 = 0, num3 = 0, temp = 0;
char op;
for (char i : s)
{
if (i >= '0'&&i <= '9')
{
if (temp == 0)
{
num1 = num1 * n + (i - '0');
}
else if (temp == 1)
{
num2 = num2 * n + (i - '0');
}
else if (temp == 2)
{
num3 = num3 * n + (i - '0');
}
if (i - '0' >= n)
{
return false;
}
}
else if (i >= 'A'&&i <= 'F')
{
if (temp == 0)
{
num1 = num1 * n + (i - 'A') + 10;
}
else if (temp == 1)
{
num2 = num2 * n + (i - 'A') + 10;
}
else if (temp == 2)
{
num3 = num3 * n + (i - 'A') + 10;
}
if (i - 'A' + 10 >= n)
{
return false;
}
}
else if (i == '+' || i == '-' || i == '*' || i == '/')
{
op = i;
temp = 1;
}
else if (i == '=')
{
temp = 2;
}
}
if (op == '+')
{
if (num1 + num2 == num3)
{
return true;
}
}
if (op == '-')
{
if (num1 - num2 == num3)
{
return true;
}
}
if (op == '*')
{
if (num1*num2 == num3)
{
return true;
}
}
if (op == '/')
{
if ((double)(num1*1.0 / (1.0*num2)) == (double)num3)
{
return true;
}
}
return false;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
string s;
while (cin >> s)
{
ll res = -1;
for (int i = 2; i <= 16; i++)
{
if (check(s, i))
{
res = i;
break;
}
}
cout << res << endl;
}
return 0;
}