Description
给定 \(n,k\),计算长度为 \(n\) 的第 \(k\) 个格雷码。
Solution
到第 \(n\) 位时,先判断 \(k<2^{n}\) 是否成立,如果成立则该位填 \(0\),否则该位填 \(1\),并且令 \(k=2^{n+1}-k\)。
#include <bits/stdc++.h>
using namespace std;
#define int unsigned long long
const int N = 1000005;
signed main()
{
freopen("code.in","r",stdin);
freopen("code.out","w",stdout);
signed n;
int k;
cin>>n>>k;
for(signed i=n-1;i>=0;--i)
{
if(k<(1ull<<i))
{
cout<<0;
}
else
{
cout<<1;
if(i+1==64) k=-k-1;
else k=(1ull<<(i+1))-k-1;
}
}
}