Find the value of N XOR’ed to itself K times
Last Updated :
06 Sep, 2021
Given two integer N and K, the task is to find the value of N XOR N XOR N XOR N … XOR N (K times).
Examples:
Input: N = 123, K = 3
Output: 123
(123 ^ 123 ^ 123) = 123
Input: N = 123, K = 2
Output: 0
(123 ^ 123) = 0
Naive approach: Simply run a for loop and xor N, K times.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int xorK( int n, int k)
{
int res = n;
for ( int i = 1; i < k; i++)
res = (res ^ n);
return res;
}
int main()
{
int n = 123, k = 3;
cout << xorK(n, k);
return 0;
}
|
Java
class GFG
{
static int xorK( int n, int k)
{
int res = n;
for ( int i = 1 ; i < k; i++)
res = (res ^ n);
return n;
}
public static void main(String[] args)
{
int n = 123 , k = 3 ;
System.out.print(xorK(n, k));
}
}
|
Python3
def xorK(n, k):
res = n
for i in range ( 1 , k):
res = (res ^ n)
return n
n = 123
k = 3
print (xorK(n, k))
|
C#
using System;
class GFG
{
static int xorK( int n, int k)
{
int res = n;
for ( int i = 1; i < k; i++)
res = (res ^ n);
return n;
}
static public void Main ()
{
int n = 123, k = 3;
Console.Write(xorK(n, k));
}
}
|
Javascript
<script>
function xorK(n, k)
{
let res = n;
for (let i = 1; i < k; i++)
res = (res ^ n);
return n;
}
let n = 123, k = 3;
document.write(xorK(n, k));
</script>
|
Time Complexity: O(K)
Space Complexity: O(1)
Efficient approach: From the properties X XOR X = 0 and X ^ 0 = X, it can be observed that when K is odd then the answer will be N itself else the answer will be 0.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int xorK( int n, int k)
{
if (k % 2 == 1)
return n;
return 0;
}
int main()
{
int n = 123, k = 3;
cout << xorK(n, k);
return 0;
}
|
Java
class GFG
{
static int xorK( int n, int k)
{
if (k % 2 == 1 )
return n;
return 0 ;
}
public static void main(String[] args)
{
int n = 123 , k = 3 ;
System.out.print(xorK(n, k));
}
}
|
Python3
def xorK(n, k):
if (k % 2 = = 1 ):
return n
return 0
n = 123
k = 3
print (xorK(n, k))
|
C#
using System;
class GFG
{
static int xorK( int n, int k)
{
if (k % 2 == 1)
return n;
return 0;
}
public static void Main(String[] args)
{
int n = 123, k = 3;
Console.Write(xorK(n, k));
}
}
|
Javascript
<script>
function xorK(n, k)
{
if (k % 2 == 1)
return n;
return 0;
}
let n = 123, k = 3;
document.write(xorK(n, k));
</script>
|
Time Complexity: O(1)
Space Complexity: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...