假设我们有两个整数x和n,我们的任务是搜索长度大于或等于n的值的第一个连续的1s(32位二进制)流,并返回其位置。如果不存在这样的字符串,则返回-1。例如,如果x = 35,并且n = 2,则结果将为31。32位整数中35的二进制表示类似于-
00000000000000000000000000000000100011。因此在索引31处出现两个连续的1,因此答案为31。
为了解决这个问题,我们必须找到前导零的数量,然后从该计数中找出连续的1。让我们看一下示例以获得更好的主意。
#include<iostream> using namespace std; int leadingZeroCount(int x) { unsigned y; int n; n = 32; for(int i = 16; i > 1; i = i/2 ){ y = x >> i; if(y != 0){ n -= i; x = y; } } y = x >> 1; if (y != 0) return n - 2; return n - x; } int consecutiveOnePosition(unsigned x, int n) { int k, p; p = 0; while (x != 0) { k = leadingZeroCount(x); x = x << k; p = p + k; k = leadingZeroCount(~x); if (k >= n) return p + 1; x = x << k; p = p + k; } return -1; } int main() { int x = 35; int n = 2; cout << "Consecutive 1s of length " << n << " is starting from index: " << consecutiveOnePosition(x, n); }
输出结果
Consecutive 1s of length 2 is starting from index: 31