[0, N] 范围内的整数 K 的计数,使得 (K XOR K+1) 等于 (K+2 XOR K+3)
给定一个整数N ,任务是打印所有小于或等于N的非负整数K的计数,使得K和K+1的按位异或等于K+2和K+3的按位异或。
例子:
Input: N = 3
Output: 2
Explanation:
The numbers satisfying the conditions are:
- K = 0, the bitwise XOR of 0 and 1 is equal to 1 and the bitwise xor of 2 and 3 is also equal to 1.
- K = 2, the bitwise XOR of 2 and 3 is equal to 1 and the bitwise xor of 4 and 5 is also equal to 1.
Therefore, there are 2 numbers satisfying the condition.
Input: 4
Output: 3
朴素方法:最简单的方法是在范围[0, N]上进行迭代并检查当前数字是否满足条件。如果满足,则将计数增加1 。检查所有数字后,打印计数值。
时间复杂度: O(N)
辅助空间: O(1)
有效方法:上述方法可以通过观察[0, N]范围内的所有偶数满足给定条件来优化。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to count all the integers
// less than N satisfying the given
// condition
int countXor(int N)
{
// Store the count of even
// numbers less than N+1
int cnt = N / 2 + 1;
// Return the count
return cnt;
}
// Driver Code
int main()
{
// Given Input
int N = 4;
// Function Call
cout << countXor(N);
return 0;
}
Java
// Java Program for the above approach
import java.io.*;
class GFG
{
// Function to count all the integers
// less than N satisfying the given
// condition
static int countXor(int N)
{
// Store the count of even
// numbers less than N+1
int cnt = (int) N / 2 + 1;
// Return the count
return cnt;
}
// Driver Code
public static void main(String[] args)
{
// Given Input
int N = 4;
// Function Call
System.out.println(countXor(N));
}
}
// This code is contributed by Potta Lokesh
Python3
# Python 3 program for the above approach
# Function to count all the integers
# less than N satisfying the given
# condition
def countXor(N):
# Store the count of even
# numbers less than N+1
cnt = N // 2 + 1
# Return the count
return cnt
# Driver Code
if __name__ == '__main__':
# Given Input
N = 4
# Function Call
print(countXor(N))
# This code is contributed by SUTENDRA_GANGWAR.
C#
// C# program for the above approach
using System;
class GFG{
// Function to count all the integers
// less than N satisfying the given
// condition
static int countXor(int N)
{
// Store the count of even
// numbers less than N+1
int cnt = (int)N / 2 + 1;
// Return the count
return cnt;
}
// Driver code
static void Main()
{
// Given Input
int N = 4;
// Function Call
Console.WriteLine(countXor(N));
}
}
// This code is contributed by abhinavjain194
Javascript
输出
3
时间复杂度: O(1)
辅助空间: O(1)