实现说明
位运算格雷码序列(JavaScript)以函数 grayCode、grayToBinary、popcount为骨架。
for (let i = 0; i < count; i++) result.push(i ^ (i >>> 1)); 与 while (gray >>> 1) { gray >>>= 1; bin ^= gray; } 嵌套——内层在外层的每一步各跑一遍。
常见问题
在一个没有任何依赖声明的空项目里能跑吗?
可以——空项目原样能跑,因为什么都不用声明。 文件在加载时定义 grayCode、grayToBinary、popcount。
签名一览:function grayCode(n)
核心语句
return (x * 0x01010101) >>> 24;
代码示例
function grayCode(n) {
const result = [];
const count = 1 << n;
for (let i = 0; i < count; i++) result.push(i ^ (i >>> 1));
return result;
}
function grayToBinary(gray) {
let bin = gray;
while (gray >>> 1) { gray >>>= 1; bin ^= gray; }
return bin;
}
function popcount(x) {
x = x - ((x >>> 1) & 0x55555555);
x = (x & 0x33333333) + ((x >>> 2) & 0x33333333);
x = (x + (x >>> 4)) & 0x0f0f0f0f;
return (x * 0x01010101) >>> 24;
}