另一种实施方式< in C

问题描述 投票:0回答:1

我无法编写正确的代码来返回 1 + x if x < 5, return 1 otherwise.

问题说明:

  • 如果 x < 5, return 1 otherwise (this ensures that 1<=x<=5)
  • ,则返回 1 + x
  • 示例计数器1To5(2) = 3
  • 示例计数器1To5(5) = 1
  • 允许使用的运算符:~ & ! | + << >>
  • 最大操作人数:15人

这是我到目前为止所拥有的:

int counter1To5(int x) {
  return ((x + ~4) >> 31) & (x + 1);
}
c count bit-manipulation computer-science bitwise-operators
1个回答
0
投票

我不会发布完整的答案,但我想您正在寻找某种 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
。请注意,我不是专家,也不是专家。我没有考虑负值,可能有更聪明的方法来解决你的问题。如果这是作业,毫无疑问你的教授会自豪地给你看。

编辑:是的

>>
对于可移植代码来说是有风险的事情,但这几乎不是他想在某个地方真正实现的东西。

© www.soinside.com 2019 - 2024. All rights reserved.