查找范围 [2, N] 中的所有 M 使得直到 M 的按位或等于直到 M-1 的值
给定一个整数N ,任务是在[2, N]范围内找到所有可能的整数M ,使得直到 M 的所有正值的按位或与直到M-1的所有正值的按位或相同。
例子:
Input: N = 4
Output: 1
Explanation: Bitwise OR till 3 = 1 | 2 | 3 = 3.
Bitwse OR till 2 = 1 | 2 = 3.
Input: N = 7
Output: 4
方法:解决此问题的方法基于以下观察:
Consider p(x) to the bitwise OR till x. So p(x) = 1 | 2 | 3 | . . . | (x-1) | x
Given p(x) = 1 | 2 | 3 | . . . | x – 1 | x. Therefore, p(x + 1) will be different from p(x) if there is a new “1” bit in (x + 1) that isn’t present in the binary sequence of p(x).
Now, let us observe the pattern:Decimal Number Binary Number 1 1 2 10 3 11 4 100 5 101 6 110 7 111 8 1000 9 1001
We can see that a new “1” bit that hasn’t previously appeared in the range [1, x] appears at every power of 2.
As such, p(x) = 1 | 2 | 3 | . . . | x – 1 | x
= 2a+1 – 1, where a = log2x.
This implies that, for a given a, there will be ( 2a + 1 – 2a – 1 ) values of x where p(x) = p(x – 1).
请按照以下步骤解决此问题:
- 计算a = log 2 N。
- 迭代从1到a的 2 的幂(例如使用变量exp ),并将ans (最初为 0)增加(2 exp + 1 – 2 exp – 1) 。
- 最后,计算N和2 a之间的对 通过将(n – 2 a )添加到ans 。
C++
// C++ code to implement the approach
#include
using namespace std;
// Function to calculate
// total matches in the range
int checkXORrange(int n)
{
int ans = 0;
int a = log2(n);
for (int exp = 1; exp <= a; exp++)
ans += pow(2, exp) - pow(2, exp - 1) - 1;
ans += n - pow(2, a);
return ans;
}
// Driver code
int main()
{
int N = 7;
// Function call
cout << checkXORrange(N) << endl;
return 0;
}
C
// C code to implement the approach
#include
#include
// Function to calculate
// total matches in the range
int checkXORrange(int n)
{
int ans = 0;
int a = log2(n);
for (int exp = 1; exp <= a; exp++)
ans += pow(2, exp) - pow(2, exp - 1) - 1;
ans += n - pow(2, a);
return ans;
}
// Driver code
int main()
{
int N = 7;
// Function call
printf("%d\n", checkXORrange(N));
return 0;
}
Python3
# Python3 code to implement the approach
import math
# Function to calculate
# total matches in the range
def checkXORrange(n):
ans = 0
a = int(math.log2(n))
for exp in range(1, a + 1):
ans += 2 ** exp - 2 ** (exp - 1) - 1
ans += n - 2 ** a
return ans
# Driver Code
if __name__ == "__main__":
N = 7
print(checkXORrange(N))
4
时间复杂度: O(log 2 N)
辅助空间: O(1)