codeforces 1560D Make a Power of Two

链接:

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值