MCPcopy Create free account
hub / github.com/Ainevsia/Leetcode-Rust / grayCode

Method grayCode

89. Gray Code/Solution.cpp:17–31  ·  view source on GitHub ↗

it requires prior knowledge: the graycode can be converted from normal binary for n bits labeled from n-1, n-2, .. 0, here is the formula: GrayBit(i) = NormalBit(i) xor NormalBit(i-1)

Source from the content-addressed store, hash-verified

15 // for n bits labeled from n-1, n-2, .. 0, here is the formula:
16 // GrayBit(i) = NormalBit(i) xor NormalBit(i-1)
17 vector<int> grayCode(int n) {
18 unsigned long long binary = 0;
19 int len = pow(2,n);
20 vector <int > res (len, 0);
21 for (int i=0; i<len; i ++, binary ++) {
22 unsigned long long t = 0;
23 for (int j=0; j<n; j ++) {
24 int shift = n - j - 1;
25 t <<= 1;
26 t ^= ((binary >> shift) & 1) xor ((binary >> (shift + 1)) & 1);
27 }
28 res[i] = t;
29 }
30 return res;
31 }
32};
33
34int main() {

Callers 1

mainFunction · 0.80

Calls 1

powFunction · 0.85

Tested by

no test coverage detected