Gray hair is God’s graffiti. Bill Cosby
We are going to generate a sequence of integers in binary. Start with the sequence 0 1 — Reflect it in the horizontal line, prepend a zero to the numbers in the top half and a one to the numbers on the bottom and you will get 00 01 11 10 Repeat this again, and you will have 8 numbers 000 0 001 1 011 3 010 2 110 6 111 7 101 5 100 4 The corresponding decimal values are shown on the right. These sequences are called Reflected Gray Codes for 1, 2 and 3 bits respectively. A Gray Code for n bits is a sequence of 2n different n-bit integers with the property that every two neighbouring integers differ in exactly one bit. A Reflected Gray Code is a Gray Code constructed in the way shown above. Input The first line of input gives the number of cases, N (at most 250000). N test cases follow. Each one is a line with 2 integers: n (1 ≤ n ≤ 30) and k (0 ≤ k < 2^n). Output For each test case, output the integer that appears in position k of the n-bit Reflected Gray Code. Sample Input 14 1 0 1 1 2 0 2 1 2 2 2 3 3 0 3 1 3 2 3 3 3 4 3 5 3 6 3 7 Sample Output 0 1 0 1 3 2 0 1 3 2 6 7 5 4
问题链接:UVA11173 Grey Codes 问题简述:(略) 问题分析: 有关Grey码计算问题,不解释 。 程序说明:(略) 参考链接:(略) 题记:(略)
AC的C++语言程序如下:
/* UVA11173 Grey Codes */ #include <bits/stdc++.h> using namespace std; const int N = 30; int grey(int n) { if(n != 0 && n != 1) { for (int i = 0; i <= N; i++) if (n >= (1 << i) && n < (1 << (i + 1))) return (1 << i) + grey((1 << (i + 1)) - n - 1); } return n; } int main() { int t, n, k; scanf("%d", &t); while (t --) { scanf("%d%d", &n, &k); printf("%d\n", grey(k)); } return 0; }