[英]How to get the number represented by least-significant non-zero bit efficiently
For example, if it is 0xc0, then the result is 0x40, Since 0xc0 is equal to binary 11000000, the result should be 01000000. 例如,如果它是0xc0,则结果为0x40。由于0xc0等于二进制值11000000,所以结果应为01000000。
public static byte Puzzle(byte x) {
byte result = 0;
byte[] masks = new byte[]{1,2,4,8,16,32,64,128};
foreach(var mask in masks)
{
if((x&mask)!=0)
{
return mask;
}
}
return 0;
}
This is my current solution. 这是我目前的解决方案。 It turns out this question can be solved in 3-4 lines... 原来这个问题可以用3-4行解决...
public static byte Puzzle(byte x) {
return (byte) (x & (~x ^ -x));
}
if x is bbbb1000, ~x is BBBB0111 (B is !b) 如果x是bbbb1000,〜x是BBBB0111(B是!b)
-x is really ~x+1, (2's complement) so adding 1 to BBBB0111 is BBBB1000 -x确实是〜x + 1,(2的补码),因此将BBBB0111加1就是BBBB1000
~x ^ -x then is 00001111 & with x gives the lowest 1 bit. 〜x ^ -x然后为00001111,其中x给出最低的1位。
A better answer was supplied by harold in the comments 哈罗德在评论中提供了一个更好的答案
public static byte Puzzle(byte x) {
return (byte) (x & -x);
}
Maby not the best solution, but you can prepare an array byte[256], store the result for each number and then use it. Maby不是最好的解决方案,但是您可以准备一个数组字节[256],存储每个数字的结果,然后使用它。
Another solution in 1 line: 1行中的另一个解决方案:
return (byte)((~(x | (x << 1) | (x << 2) | (x << 3) | (x << 4) | (x << 5) | (x << 6) | (x << 7) | (x << 8)) + 1) >> 1);
Hardly a 1-line solution, but at least it doesn't use the hardcoded list of the bits. 几乎不是一线解决方案,但至少它不使用位的硬编码列表。
I'd do it with some simple bit shifting. 我会做一些简单的移动。 Basically, down-shifting the value until the lowest bit is not 0, and then upshifting 1 with the amount of performed shifts to reconstruct the least significant value. 基本上,将值向下移位直到最低位不为0,然后再按执行移位的数量向上移位1以重建最低有效值。 Since it's a 'while' it needs an advance zero check though, or it'll go into an infinite loop on zero. 由于它是一个“ while”,因此它需要提前进行零位检查,否则它将在零上进入无限循环。
public static Byte Puzzle(Byte x)
{
if (x == 0)
return 0;
byte shifts = 0;
while ((x & 1) == 0)
{
shifts++;
x = (Byte)(x >> 1);
}
return (Byte)(1 << shifts);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.