在C++中查詢數字二進位制表示中長度>=n的連續1
假設我們有兩個整數x和n,我們的任務是在32位二進位制數中搜索第一個長度大於或等於n的連續1的序列,並返回其位置。如果不存在這樣的序列,則返回-1。例如,如果x = 35,n = 2,則結果將為31。35的32位整數二進位制表示如下:
00000000000000000000000000100011。因此,在索引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
廣告