Acwing 2058.笨拙的手指 (进制转换,暴力枚举)
题目链接
https://www.acwing.com/problem/content/2060/
思路
将二进制数的每个位置的数改一下,将得到的十进制加入哈希表,枚举三进制可能改的数字之后,查找哈希表,找到的即为唯一答案。
AC代码
#include <iostream>
#include <string>
#include <unordered_set>
#include <cmath>
using namespace std;
unordered_set<int>v;
bool flag = false;
void to_two(string s)
{
int sum = 0;
for (int i = 0; i <s.size(); i++)
{
sum = sum * 2 + s[i] - '0';//秦九韶算法
}
v.insert(sum);
}
void to_three(string s)
{
int sum = 0;
for (int i = 0; i < s.size(); i++)
{
sum = sum * 3 + s[i] - '0';
}
if (v.find(sum) != v.end())
{
cout << sum;
flag = true;
}
}
int main(int argc, char* argv[])
{
string n2;
string n3;
cin >> n2 >> n3;
for (int i = 0; i < n2.size(); i++)
{
if (n2[i] == '0')
{
n2[i] = '1';
to_two(n2);
n2[i] = '0';
}
else
{
n2[i] = '0';
to_two(n2);
n2[i] = '1';
}
}
for (int i = 0; i < n3.size() && !flag; i++)
{
if (n3[i] == '0')
{
n3[i] = '1';
to_three(n3);
n3[i] = '2';
to_three(n3);
n3[i] = '0';
}
else if (n3[i] == '1')
{
n3[i] = '0';
to_three(n3);
n3[i] = '2';
to_three(n3);
n3[i] = '1';
}
else if (n3[i] == '2')
{
n3[i] = '1';
to_three(n3);
n3[i] = '0';
to_three(n3);
n3[i] = '2';
}
}
}
心得
代码写的啰嗦了一点,暴力没有太多思维难度。