【发布时间】:2022-04-25 02:31:45
【问题描述】:
我有一个字节,我想将剩下的第一个位增加 1(上下文是一个小的康威生命游戏)。
示例:11 是0000 1011:
- 我想增加
101 - 5 + 1 = 6 是
110 - 将第一位重置为初始状态
- 字节现在是
0000 1101,即13问题:
- 有没有办法让
addNeighbour继续作为空白方法(我找不到方法不是返回num)? - 有没有更好的方法来执行
addNeighbour操作:
const getBinaryRepresentation = (number) => { let str = \"\"; for (let i = 7; i >= 0; i--) { ((number & (1 << i)) != 0) ? str += \"1\" : str += \"0\"; } console.log(str) } let num = 5; getBinaryRepresentation(num) // 0000 0101 const addNeighbour = (num) => { const isAlive = num & 1; const neighbours = num >> 1; num = (neighbours + 1) << 1; if (isAlive === 1) num |= (1 << 0) return num; } num = addNeighbour(num); getBinaryRepresentation(num) // 0000 0111 - 有没有办法让
-
如果你删除
return num它不会返回任何东西,也就是返回 void ... -
是的,但
num的实际值不受影响,getBinaryRepresentation(num)将返回 0000 0101 -
“第一位”是指 LSB?
-
@Bergi 完全!
标签: javascript bitwise-operators bit-shift arrow-functions