【CSP - S T1】格雷码

L i n k Link

l u o g u luogu P 5657 P5657

D e s c r i p t i o n Description

在这里插入图片描述

S a m p l e Sample I n p u t Input 1 1

2 3

S a m p l e Sample O u t p u t Output 1 1

10

S a m p l e Sample I n p u t Input 2 2

3 5

S a m p l e Sample O u t p u t Output 2 2

111

S a m p l e Sample I n p u t Input 3 3

44 1145141919810

S a m p l e Sample O u t p u t Output 3 3

00011000111111010000001001001000000001100011

H i n t Hint

T r a i n Train o f of T h o u g h t Thought

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

C o d e Code

#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;
		 } 
	}
}

猜你喜欢

转载自blog.csdn.net/LTH060226/article/details/103431872
今日推荐