Flip the Bits(思维)
2024-08-24 20:18:29
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 n such 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
2
5
10
Output
1
2 题目意思:将一个2进制的n中每个位翻转得到一个比n小且尽可能大的数,求输出翻转了几位。 解题思路:这道题该由我背锅,我当时先是翻译错了题意,后来稍微有一点眉目了,我又理解错了那个flip的意思,这里面的翻转并不是那种交换(swap那样的),而是像硬币正面换到反面那样的翻转,也就
是0与1的交换,根据题意可以推出想要得到一个既要比n小还有尽可能大的数,只有是n前面的那一个数n-1。所以就是根据n构造一个二进制的n-1,方法就是找到n的二进制中最后面的那一个1翻转为0,而最
后一个1之后的0全都翻转成1,统计所用的翻转次数即可。
#include<cstdio>
#include<cstring>
int main()
{
int t,n,j,k,i,count;
int a[];
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
memset(a,-,sizeof(a));
j=;
count=;
i=n;
while(i)
{
a[j]=i%;
if(a[j]==)
{
count++;
}
if(a[j]==)
{
count++;
break;
}
i/=;
j++;
}
printf("%d\n",count);
}
return ;
}
最新文章
- 希尔排序(java)
- 配置tomcat https
- 【代码笔记】iOS-日历
- Java Se :Map 系列
- Dubbo系列(1)_背景介绍和基本情况
- HTTP返回值
- [ruby on rails] 跟我学之(5)显示所有数据
- vmware shared holder 虚拟机设置共享目录
- linux 下安装redis以及php Redis扩展
- oracle 字符串切割成结果集方法
- akka简单示例-2
- hdu4370 0 or 1【最短路+建图】
- CSS: inline-block的应用和float块高度塌陷
- bzoj3110: [Zjoi2013]K大数查询 【cdq分治&;树套树】
- 中文分词工具thulac4j正式发布
- gb_tree平衡树源码
- jenkins添加类ubuntu/centos节点报错
- 彻底填平Static坑(细节决定成败)
- luogu P3312 [SDOI2014]数表
- virtual box 安装centos min
热门文章
- Spring 约束文件配置
- TinyMCE插件:RESPONSIVE filemanager 9 安装与配置
- Mongo DB命令简介
- hive错误排查一:hive中执行 drop table命令卡住,删除表不成功
- 目标反射回波检测算法及其FPGA实现 之一:算法概述
- 详解LeetCode 137. Single Number II
- Oracle入门第二天(下)——单行函数
- 20155216 2016-2017-2 《Java程序设计》第一周学习总结
- 20155233 2006-2007-2 《Java程序设计》第4周学习总结
- 20155318 2016-2017-2《Java程序设计》课程总结