【44】89. Gray Code
89. Gray Code
Description Submission Solutions Add to List
- Total Accepted: 80601
- Total Submissions: 203541
- Difficulty: Medium
- Contributors: Admin
The gray code is a binary numeral system where two successive values differ in only one bit.
Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.
For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:
00 - 0 01 - 1 11 - 3 10 - 2
1 class Solution { 2 public: 3 vector<int> grayCode(int n) { 4 vector<int> res; 5 for(int i = 0; i < pow(2, n); i++){ 6 res.push_back((i >> 1) ^ i); 7 } 8 return res; 9 } 10 };

浙公网安备 33010602011771号