Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Gray Code - รหัสเกรย์ใน C++


ภาพรวมปัญหา

Gray Code เป็นระบบเลขฐานสองที่ค่าติดกันต่างกันแค่ 1 บิต กำหนด n บิต ต้องสร้างลำดับ Gray Code เริ่มจาก 0

ตัวอย่าง: n=2 → [0,1,3,2] (00, 01, 11, 10)

สูตรการแปลง

Gray code ของ i = i XOR (i >> 1)

ตัวอย่างโค้ด C++

#include <bits/stdc++.h>
using namespace std;

void print_vector(vector<int> v){
    cout << "[";
    for(int i = 0; i < v.size(); i++) cout << v[i] << ", ";
    cout << "]" << endl;
}

class Solution {
public:
    vector<int> grayCode(int n) {
        vector <int> ans;
        for(int i = 0; i < (1<> 1));
        return ans;
    }
};

int main(){
    Solution ob;
    print_vector(ob.grayCode(4));
}

Input / Output

Input:  4
Output: [0, 1, 3, 2, 6, 7, 5, 4, 12, 13, 15, 14, 10, 11, 9, 8]