D. Make a Power of Two
题意:
给定一个整数n,对它可以进行下面2种操作
1.删除一个数字
2.添加一个数字
求把它变成一个2的整数次幂最少操作次数
思路:
首先n的范围是1e9,所以最多涉及到的,也就10多位,完全可以先把2的整数次幂预处理出来,然后统计这个数变成其中每一个数字需要的次数,取一个最小值
#include <iostream>
#include <string>
#include <vector>
#include <cmath>
using namespace std;
const int N = 1e7;
long long M = 1e9 + 10;
vector<string> s;
int a[11],b[11];
void init()
{
for(int i = 0;i < 64;i ++)
{
long long x = pow(2,i);
string t = to_string(x);
s.push_back(t);
}
}
int main()
{
init();
int t;
cin >> t;
// for(auto x:s) cout << x << endl;
while(t --)
{
string c;
cin >> c;
int res = 0x3f3f3f3f;
for(auto x:s)
{
int ans = 0;
int cnt = 0;
for(int i = 0,j = 0;i < x.size();i ++)
{
while(j < c.size() && c[j] != x[i]) j ++;
if(c[j] == x[i]) cnt ++;
else break;
j ++;
}
ans = c.size() - cnt;
if(cnt < x.size()) ans += x.size() - cnt;
res = min(res,ans);
//if(c == "301" && res == 1) cout << x << endl;
}
cout << res << endl;
}
return 0;
}