Средне Решено: 0 Процент решений: 0%

Gray Code

List the n-bit reflected binary Gray code, where neighbors differ in exactly one bit.

Чему вы научитесь

  • Compute a Gray code with XOR and shift
  • Generate 2^n values
  • Check that neighbors differ in one bit

Условие

Показать перевод

In a Gray code sequence each value differs from the previous one in exactly one bit. The standard (reflected binary) Gray code of i is i XOR (i >> 1): for 2 bits the sequence is 0, 1, 3, 2, which is 00, 01, 11, 10 in binary. Rotary encoders use it so that a reading taken between two positions is never wildly wrong.

Implement gray_code(n).

Input

n: The number of bits.

Output

Return the 2^n values of the reflected binary Gray code in order, as integers, starting with 0. For n = 0 return [0].

Ограничения

0 ≤ n ≤ 16

Примеры

Пример 1
Ввод:
n = 2

Ожидаемый вывод:
expected = [0, 1, 3, 2]
Ввод:
long long n = 2;

Ожидаемый вывод:
std::vector<long long> expected = {0, 1, 3, 2};
Ввод:
long n = 2;

Ожидаемый вывод:
long[] expected = new long[] {0, 1, 3, 2};

Пояснение

In binary the sequence is 00, 01, 11, 10, so the answer is [0, 1, 3, 2].

Пример 2
Ввод:
n = 3

Ожидаемый вывод:
expected = [0, 1, 3, 2, 6, 7, 5, 4]
Ввод:
long long n = 3;

Ожидаемый вывод:
std::vector<long long> expected = {0, 1, 3, 2, 6, 7, 5, 4};
Ввод:
long n = 3;

Ожидаемый вывод:
long[] expected = new long[] {0, 1, 3, 2, 6, 7, 5, 4};

Пояснение

Each value is i XOR (i >> 1) for i = 0 to 7: [0, 1, 3, 2, 6, 7, 5, 4].

Как подступиться

Сначала попробуйте сами, затем открывайте подсказки по одной.

Подсказка 1

Loop i from 0 to 2^n − 1.

Подсказка 2

Each Gray code value comes from i and i shifted right by one.

Подсказка 3

For n = 0 the loop runs once and gives [0].

Ожидаемая сложность

O(2^n) time, O(2^n) extra space

Ссылки

Это задание адаптировано для CodeUtility. Следуйте условию и ограничениям выше.

Лучшее принятое решение каждого участника. Более быстрые, экономные и высоко оценённые решения стоят выше.

Принятых решений пока нет. Решите задачу и займите первое место.

Учитесь у других

Решения сообщества

Пока нет опубликованных решений. Решите задание, чтобы поделиться первым.