链接:
https://codeforces.com/problemset/problem/1560/D
题意:
通过删除和增加数字使n变成2的任意幂次方。找到能达到要求的最小操作次数。
本题让n和所有2的幂次比较,找到最小值。n变成任意2的幂次需要的操作次数,是(n的长度-n和该数最多能匹配的数)(即n要删除的数的个数)+(该数的长度-n和该数最多能匹配的数)(即n要增加的数的个数)。还要考虑2的0次幂的情况。
代码如下:
#include<iostream>
#include<vector>
#include<cmath>
#include<set>
#include<algorithm>
#include<string>
#include<string.h>
#include<random>
#include<queue>
using namespace std;
typedef long long ll;
vector<string>v;
int pro(string a, string b) {
int alen = a.size();
int blen = b.size();
int cnt = 0;
int x = 0, y = 0;
while (x < alen && y < blen) {
if (a[x] == b[y]) {
cnt++;
y++;
}
x++;
}
return alen - cnt + blen - cnt;
}
int main() {
for (ll i = 1; i <= 1e18; i *= 2) {
v.push_back(to_string(i));
}
int T;
cin >> T;
while (T--) {
string n;
cin >> n;
int ans = n.size() + 1;
for (auto i : v) {
ans = min(ans, pro(n, i));
}
cout << ans;
cout << endl;
}
return 0;
}