【CSP - S T1】格雷码

LinkLink

luoguluogu P5657P5657

DescriptionDescription

在这里插入图片描述

SampleSample InputInput 11

2 3

SampleSample OutputOutput 11

10

SampleSample InputInput 22

3 5

SampleSample OutputOutput 22

111

SampleSample InputInput 33

44 1145141919810

SampleSample OutputOutput 33

00011000111111010000001001001000000001100011

HintHint

TrainTrain ofof ThoughtThought

kk在当前个数的左边(对于中间值而言),则当前位为0(这一边的上一位不是1)
kk在当前个数的右边(同上),则当前位为1(同上)
若上一位为1,则将上述规律调换一遍

CodeCode

#include<iostream>
#include<cstdio>
#define ull unsigned long long 

int n;
ull k;

using namespace std;

int main()
{
	ull l, r; 
	scanf("%d", &n);
	cin >> k;
	if (n == 64) {
		return !printf("1000000000000000000000000000000000000000000000000000000000000000");//对数据的特判
	}
	 else l = 1, r = 1ull << n;
	bool pd = 0;
	while (l < r)
	{
		ull mid =(ull) (l + r) >> 1;//取中间值
		if (k < mid) {
			r = mid; 
			if (pd == 1) printf("1"), pd = 0;
			 else printf("0");//同思路(pd判断上一位是否为1)
		} 
		 else {
		 	l = mid + 1;
		 	if (pd == 1) printf("0");
		 	 else printf("1");//同上
		 	pd = 1;
		 } 
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章