给定范围内 x 的计数,使得 x、(x+1) 和 (x+2)、(x+3) 的按位异或相等
给定一个整数N ,任务是计算[0, 2 N -1]范围内的整数个数(比如x ),使得x⊕(x+1) = (x+2)⊕(x+3) . [其中⊕代表按位异或]
例子:
Input: N = 1
Output: 1
Explanation: Only 0 is the valid x, as, 0 ⊕ 1 = 2 ⊕ 3 = 1
Input: N = 3
Output: 4
朴素方法:解决给定问题的简单方法是生成 x 在[0, 2 N -1]范围内的所有可能值,并检查它们是否满足给定标准,即x⊕(x+1) = (x+ 2)⊕(x+3) 。
按照下面提到的步骤来实现这个想法:
- 从i = 0 迭代到 N 。
- 检查(i ⊕ (i+1)) = ((i+2) ⊕ (i+3))
- 如果满足条件,则增加此类数字的计数。
- 返回最终计数作为答案。
下面是上述方法的实现:
Python3
# Python3 code to implement the approach
# Function to find number of integers
# satisfying the condition
def countOfvalues(N):
# Stores the resultant count of pairs
count = 0
for i in range(0, 2**N):
# Iterate over the range
if i ^ (i + 1) == (i + 2) ^ (i + 3):
count += 1
return count
# Driver Code
if __name__ == '__main__':
N = 3
# Function call
print(countOfvalues(N))
Python3
# Python code to implement the above approach
# Function to calculate
# the number of possible values
def countOfValues (N):
return pow(2, N - 1)
# Driver code
if __name__ == '__main__':
N = 3
# Function call
res = countOfValues(N)
print(res)
4
时间复杂度: O(2 N )
辅助空间:O(1)
Efficient Approach:这个问题可以基于以下数学思想高效解决:
- If x is such that it is a even number then x+2 is also a even number and both (x+1) and (x+3) will be odd numbers.
- Now two consecutive even and odd number has only a single bit difference only on their LSB position.
- So the bitwise XOR of (x and x+1) and (x+2 and x+3) both will be 1, when x is even.
- Therefore all the even numbers in the given range [0, 2N−1] is a possible value of x.
So total number of such values are (2N – 1)/2 = 2N-1
按照下图更好地可视化这个想法:
插图:
Consider N = 3. So the numbers are in range [0, 7]
All even numbers in the range are 0, 2, 4 and 6
=> When x = 0: 0 ⊕ 1 = 1 and 2 ⊕ 3 = 1. Therefore the relation holds
=> When x = 2: 2 ⊕ 3 = 1 and 4 ⊕ 5 = 1. Therefore the relation holds
=> When x = 4. 4 ⊕ 5 = 1 and 6 ⊕ 7 = 1. Therefore the relation holds
=> When x = 6: 6 ⊕ 7 = 1 and 8 ⊕ 9 = 1. Therefore the relation holds.
Now for the odd numbers if it is done:
=> When x = 1: 1 ⊕ 2 = 3 and 3 ⊕ 4 = 7. Therefore the relation does not hold.
=> When x = 3: 3 ⊕ 4 = 7 and 5 ⊕ 6 = 3. Therefore the relation does not hold.
=> When x = 5: 5 ⊕ 6 = 3 and 7 ⊕ 8 = 15. Therefore the relation does not hold.
=> When x = 7: 7 ⊕ 8 = 15 and 9 ⊕ 10 = 3. Therefore the relation does not hold.
So total possible values are 4 = 23-1
因此得到答案计算2 N-1的值 对于给定的N
下面是上述方法的实现。
Python3
# Python code to implement the above approach
# Function to calculate
# the number of possible values
def countOfValues (N):
return pow(2, N - 1)
# Driver code
if __name__ == '__main__':
N = 3
# Function call
res = countOfValues(N)
print(res)
4
时间复杂度:O(1)
辅助空间:O(1)