跳到正文

个人记录

第6次练习课:T4 二进制与一

_ideal_freedom_pop_约 1 分钟
原文
文章信息与版本

文章信息

发布
2025年11月5日
收录
2025年12月12日
更新
2026年11月20日
篇幅
约 1 分钟

版本

  1. v1当前

题意分析: 给定一个正整数n,以及操作次数q对于每次操作给出一个正整数k,要求让n加上一个非负整数x,使得n 在二进制下的第 k 位(从右往左数)是 1,并在符合要求的情况下,令x最小。

那么所有的x之和是多少?

思路: 输入正整数n,以及操作次数q while,每次q— 输入一个数k 再用一个变量x存(1ll<<k) 如果(n&x)为0 创建变量y等于n%x sum加上x减y n加上x减y

最后输出sum

代码:

C++
#include<bits/stdc++.h>
#define int long long
#define endl '\n'
#define qwq ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
using namespace std;
int n,q,sum;
signed main(){
	qwq;
	cin>>n>>q;
	while(q--){
		int k;
		cin>>k;
		k--;
		int x=(1ll<<k);
		if((n&x)==0){
			int y=n%x;
			sum+=x-y;
			n+=x-y;
		}
	}
	cout<<sum;
	return 0;
}

错因: 没有思路

原文