P5657 [CSP-S2019] 格雷码
#include <iostream> #include <stdio.h> #include <algorithm> #include <string> #include <cmath> #define For(i, j, n) for(int i = j ; i <= n ; ++i) using namespace std; typedef unsigned long long Ull; const unsigned long long LIM = 18446744073709551615ull; Ull k; int n; int main() { cin >> n >> k; Ull res = 0; while(n) { //cout << "\nk :" << k << endl; Ull now = 1ull << (n - 1); //cout << "\nnow :" << now << endl; if(k < now) putchar('0'); else putchar('1'); if(k >= now) //k = (1 << n) - k - 1; { if(n == 64) k = LIM - k; else k = (1ull << n) - k - 1; } n--; } return 0; }
1.因为n最大是64,会溢出unsigned long long,所以要先打表,打出2^64-1
2.(1ull<<n)的ull不能去掉:虽然说C++在不同数据类型运算的时候会自动转换,但是要注意:
(1<<n)是被括号包起来的,所以它会最优先运算,而1默认是int类型,这里位移位数太多,直接就先溢出,全0了,后面再转unsigned long long也来不及