跳到正文

个人记录

二进制数最高位的1的位置

2018chenyu约 3 分钟
原文
文章信息与版本

文章信息

发布
2019年11月6日
收录
2026年1月1日
更新
2026年11月7日
篇幅
约 3 分钟

版本

  1. v2当前
  2. v1

蒟蒻进行二进制状压时经常为二进制数的处理技巧而烦恼,除了基本的判断第几位是否为1 -> now&(1<<i)什么的,一窍不通。


正文

如何快速获取一个二进制数最高位的 1 的位置呢? 不难想到暴力右移,O(n)O(n)(n 为二进制数的位数)也不算慢——

C++
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
inline ll read()
{
	ll x=0;bool f=false;
	char ch=getchar();
	while(ch<'0' || ch>'9') f|=(ch=='-'),ch=getchar();
	while(ch>='0'&&ch<='9') x=x*10+(ch^48),ch=getchar();
	return f?-x:x;
}
inline int _find_left_1(ull x)
{
	int n=0;
	while(x)
	{
		x>>=1;
		n++;
	}
	return n-1;
}
int main()
{
	ll n=read();
	printf("%d\n",_find_left_1(n));
	return 0;
}

但是还有不需要循环的 O(1)O(1) 神仙做法,手动模拟二分:判断最高位的 1 位于低32位还是高32位、低16位还是高16位…以此类推。

C++
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
inline ll read()
{
	ll x=0;bool f=false;
	char ch=getchar();
	while(ch<'0' || ch>'9') f|=(ch=='-'),ch=getchar();
	while(ch>='0'&&ch<='9') x=x*10+(ch^48),ch=getchar();
	return f?-x:x;
}
inline int find_left_1(ull x)//找二进制数最高位的1(64bit版)
{
	int n=1;
	if(x==0) return -1;
	if(!(x>>32)) n=n+32,x=x<<32;//采用二分法:确定是在高32位还是低32位
	if(!(x>>48)) n=n+16,x=x<<16;//确定是在高16位还是低16位...以此类推
	if(!(x>>56)) n=n+8,x=x<<8;
	if(!(x>>60)) n=n+4,x=x<<4;
	if(!(x>>62)) n=n+2,x=x<<2;
	n=n-(x>>63);
	return 63-n;
}
int main()
{
	ll n=read();
	printf("%d\n",find_left_1(n));
	return 0;
}

Orz 我还是太菜了

原文