Test instructions: Provides a number n, which represents the number of binary, then there is a 2 n chance, from 0 to 2^n-1. Turn it into a gray code, and then direct the binary Gray code to the binary reading method into an integer, loaded in the vector container back, to order (otherwise you will directly return 0~2^n-1).
Idea: what a look! What is gray code? Suppose there are 1 integers, which are in binary form, and 1 of the highest bits are raised, and each of the other bits equals the number on the bit that is different from the previous digit of the number.
Looks like a complicated look? Example: integer 21 = 0001 1012 Binary, Gray code the first 4 bits is such a 0001, this is the binary of the highest bit of 1 proposed, then Gray code of the last 4 bit? From the left, the 5th bit of gray code = binary 5th bit 0 xor ^ binary 4th bit 1 = 1, this time the gray code 5th bit appeared, gray code became 0001 1. Where's the 6th place? From the left, the Gray code of the 6th bit = binary 6th bit 1 xor ^ binary 5th bit 0 = 1, gray Code of 0001 11, the latter several believe you will forget. The result gray code is 0001 1111.
How does the above method be implemented in the computer? By law, the number on each bit of binary is the same as the previous one, even if the highest bit, because the highest bit is definitely 1 (out of the bit integer 0), and the 1 is 0, then 1 and 0 of the XOR is still 1. In this case, directly to the right of our integers, and then the original integer XOR result, is we want the gray code, although it is not read out of the original integer, but its binary form is the integer corresponding to the gray code. If there is an integer a=7, the binary is 0000 0111, changed to Gray code is 0000 0100, this gray code by the binary reading of the integer is translated into an integer is 4, this is vector[7]=4. Simple, huh?
1 classSolution {2 Public:3vector<int> Graycode (intN) {4vector<int>ans;5 intm = (1<<N);//There's a total number of M to return6Ans.resize (m);//first put the m number of 0, but also help you set up a memory, how convenient! 7 intCount =0; 8 for(intI=1; i<m; i++)//processing of the number I9 {Tencount++; OneAns[i] = (Count >>1) ^count; A } - returnans; - } the};Graycode
Leetcode Gray Code Grey Code