Given an integer N, the task is to print the count of all the non-negative integers K less than or equal to N, such that bitwise XOR of K and K+1 equals bitwise XOR of K+2 and K+3.
Examples:
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
Naive Approach: The simplest approach is to iterate over the range [0, N] and check if the current number satisfies the condition or not. If it satisfies, increment the count by 1. After checking all the numbers, print the value of the count.
Time Complexity: O(N)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized by the observation that all the even numbers in the range [0, N] satisfy the given condition.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countXor( int N)
{
int cnt = N / 2 + 1;
return cnt;
}
int main()
{
int N = 4;
cout << countXor(N);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int countXor( int N)
{
int cnt = ( int ) N / 2 + 1 ;
return cnt;
}
public static void main(String[] args)
{
int N = 4 ;
System.out.println(countXor(N));
}
}
|
Python3
def countXor(N):
cnt = N / / 2 + 1
return cnt
if __name__ = = '__main__' :
N = 4
print (countXor(N))
|
C#
using System;
class GFG{
static int countXor( int N)
{
int cnt = ( int )N / 2 + 1;
return cnt;
}
static void Main()
{
int N = 4;
Console.WriteLine(countXor(N));
}
}
|
Javascript
<script>
function countXor(N) {
let cnt = Math.floor(N / 2) + 1;
return cnt;
}
let N = 4;
document.write(countXor(N));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!