[英]Finding the bug in this java code for right cyclic shift (Codility)
Recently I was given a codility problem which says the following code has a bug .最近我收到了一个 codility 问题,它说下面的代码有一个错误。
So, the code problem is that we have a 30-bit unsigned integer from N[29]... N[0]
and performing the right cyclic shift (>>) should give us a number like N[0]N[29]... N[1]
.所以,代码问题是我们有一个来自N[29]... N[0]
的 30 位无符号整数,执行正确的循环移位 (>>) 应该给我们一个像N[0]N[29]... N[1]
。
Our goal is to find the number of right shifts which produce the maximum value achievable from a given number.我们的目标是找到产生从给定数字可实现的最大值的右移次数。
For Example:例如:
for N = 9736 (00 0000 0000 0000 0010 0110 0000 1000)对于 N = 9736 (00 0000 0000 0000 0010 0110 0000 1000)
9736 >> 1 = 4868 -> 00 0000 0000 0000 0001 0011 0000 0100 9736 >> 1 = 4868 -> 00 0000 0000 0000 0001 0011 0000 0100
. .
. .
. .
9736 >> 11 = 809500676 -> 11 0000 0100 0000 0000 0000 0000 0100 9736 >> 11 = 809500676 -> 11 0000 0100 0000 0000 0000 0000 0100
. .
. .
till 30 (as we have 30 bits integers)直到 30(因为我们有 30 位整数)
from the example above on the 11th iteration, we receive the maximum number possible for 9736. Hence the answer = 11从上面第 11 次迭代的示例中,我们得到 9736 的最大可能数。因此答案 = 11
Given Code:给定代码:
int shift(int N) {
int largest = 0;
int shift = 0;
int temp = N;
for (int i = 1; i < 30; ++i) {
int index = (temp & 1);
temp = ((temp >> 1) | (index << 29));
if (temp > largest) {
largest = temp;
shift = i;
}
}
return shift;
}
N is in range [0... 1,073,741,823] N 在 [0...1,073,741,823] 范围内
I tried but couldn't find the bug here or the test case where this fails.我试过但找不到这里的错误或失败的测试用例。
It fails for 0b10000...000
( 0x20000000
), Because the largest value is for shift
==0它失败了0b10000...000
( 0x20000000
),因为最大值是shift
==0
the simplest solution is to define largest
as N
instead of 0
.最简单的解决方案是将largest
定义为N
而不是0
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.