Flip the Bits

本文介绍了一个算法问题,即如何通过翻转二进制表示中的位来构造一个尽可能大的小于给定整数n的新数m。文章提供了一种有效的方法来计算达到这一目的所需的最小翻转次数,并分享了一个实用的C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

You are given a positive integer n. Your task is to build a number m by flipping the minimum number of bits in the binary representation of nsuch that m is less than n (m < n) and it is as maximal as possible. Can you?

Input

The first line contains an integer T (1 ≤ T ≤ 105) specifying the number of test cases.

Each test case consists of a single line containing one integer n (1 ≤ n ≤ 109), as described in the statement above.

Output

For each test case, print a single line containing the minimum number of bits you need to flip in the binary representation of n to build the number m.

Example

input

Copy

2
5
10

output

Copy

1
2

题解:就是计算n异或n-1的1的个数,看看变化几次,然后学到一个新函数__builtin_popcount(n^(n-1))来计算二进制中1的个数。

代码如下:

#include <iostream>
#include <cstdio>
#include <stdlib.h>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <string.h>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <ctime>
#define maxn 1007
#define N 100005
#define INF 0x3f3f3f3f
#define PI acos(-1)
#define lowbit(x) (x&(-x))
#define eps 0.000000001
#define read(x) scanf("%d",&x)
#define put(x) printf("%d\n",x)
#define Debug(x) cout<<x<<" "<<endl
using namespace std;
typedef long long ll;

int n;
int main()
{
    int t;
    cin>>t;
    while (t--)
    {
        cin>>n;
        cout<<__builtin_popcount(n^(n-1))<<endl;//取异或
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值