常用位操作:
(a) 将第27位设置为及格(设作1)其他位不变:
result|=(1<<27) //任意的位值与1作按位或操作其值为1,而与0作按位与操作其值不变
(b) 将第27位设置成不及格(设为0)。
result&=~(1<<27) //任意的位值与0作按位与操作其值为0,而与1作按位与操作其值不变
(c) 反转第27位的值。
result^=(1<<27) //任意的位值与1作按位异或操作其值为1,而与0作按位异与操作其值不变
[解题思路]
看到这个题时,首先做了一个模拟,当n=3时,gray code应该是
000
001
011
010
110
100
101
111
看了半天,也没看出来什么规律。后来上网一查GrayCode(http://en.wikipedia.org/wiki/Gray_code)才发现原来推导的gray code顺序错了。第六个应该是111。
n=3时,正确的GrayCode应该是
000
001
011
010
110
111 //如果按照题意的话,只是要求有一位不同,这里也可以是100
101
100
这样的话,规律就出来了,n=k时的Gray Code,相当于n=k-1时的Gray Code的逆序 加上 1<<k。
[Code]
1: vector<int> grayCode(int n) {
2: // Start typing your C/C++ solution below
3: // DO NOT write int main() function
4: vector<int> result;
5: result.push_back(0);
6: for(int i=0; i< n; i++)
7: {
8: int highestBit = 1<<i;
9: int len = result.size();
10: for(int i = len-1; i>=0; i--)
11: {
12: result.push_back(highestBit + result[i]);
13: }
14: }
15: return result;
16: }
[总结]
题意不清楚,如果每次只是与上一个数有一个位不同的话,其实有很多种组合出来。如果不是查了Gray Code的定义,根本看不出来什么规律。
而且,Gray Code这种东西,必然有数学解,否则在早期的工程界是没法应用的。想了一下,其实也可以这么做,第i个数可以由如下公式产生: (i>>1)^i,所以代码也可以是:
1: vector<int> grayCode(int n)
2: {
3: vector<int> ret;
4: int size = 1 << n;
5: for(int i = 0; i < size; ++i)
6: ret.push_back((i >> 1)^i);
7: return ret;
8: }
不过这种数学解就失去了interview的意思了。
所以二进制到格雷码:
(i>>1)^i
格雷码到二进制:
static unsigned int gray2decimal(unsigned int x) {
unsigned int y = x;
while (x >>= 1)
y^=x;
return y;
}