我无法编写正确的代码来返回 1 + x if x < 5, return 1 otherwise.
问题说明:
这是我到目前为止所拥有的:
int counter1To5(int x) {
return ((x + ~4) >> 31) & (x + 1);
}
我不会发布完整的答案,但我想您正在寻找某种 operator 方法来确定
x
是否大于 5
。
!((x - 1) >> 2)
^ ^ ^
| | |
| | Here you shift the bits that are not necessary out of the integer
| |
| By subtracting here you make sure, that 5 is the smallest integer to not
| be shifted out
|
Negating the value to get 1 or 0 as an output
我没有测试,但如果
0
确实大于 x
,则应返回 4
;如果 1
较小,则应返回 x
。请注意,我不是专家,也不是专家。我没有考虑负值,可能有更聪明的方法来解决你的问题。如果这是作业,毫无疑问你的教授会自豪地给你看。
编辑:是的
>>
对于可移植代码来说是有风险的事情,但这几乎不是他想在某个地方真正实现的东西。