题目链接:http://www.gdutcode.sinaapp.com/problem.php?cid=1057&pid=4
题解:
方法一:对n取2的对数:
取对数的公式:s = log(n)/log(2), //取整
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<queue>
#include<vector>
#include<map>
#include<string>
#include<set>
#define LL long long
#define MAX(a,b) (a>b?a:b)
#define MIN(a,b) (a<b?a:b)
#define INF 0x7fffffff
#define LNF ((1LL<<62)-1)
#define maxn 200010
using namespace std;
int main()
{
int t,n,k,s,i;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&k);
while(--k)
{
s = log(n)/log(2);//这样直接赋值的话,对n取二的对数后再取整
n -= (1<<s);
}
LL ans, b;
for(i = 1; ; i++)
{
b = 1<<i;
if(b>=n)
{
ans = b - n;
break;
}
}
printf("%d\n",ans);
}
}
2.使用lowbit()
lowbit:
lowbit(i)将i转化成二进制数之后,只保留最低位的1及其后面的0,截断前面的内容,然后再转成10进制数。
代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <sstream>
#include <algorithm>
using namespace std;
#define pb push_back
#define mp make_pair
#define ms(a, b) memset((a), (b), sizeof(a))
//#define LOCAL
typedef long long LL;
const int inf = 0x3f3f3f3f;
const int maxn = 10000+10;
const int mod = 1e9+7;
int cnt(int n){//计算n中有多少个1
int num=0;
while(n>0){
num++;
n&=(n-1);
}
return num;
}
int lowbit(int x){
return x&(-x);
}
int main()
{
#ifdef LOCAL
freopen("input.txt" , "r", stdin);
#endif // LOCAL
int T, n, k;
cin >> T;
while(T--){
cin >> n >> k;
int ans =0;
while(cnt(n)>k){
ans += lowbit(n);
n+=lowbit(n);//补上lowbit(n)个瓶子,就会进位。
}
cout << ans << endl;
}
return 0;
}