Check if the Xor of the frequency of all digits of a number N is zero or not
Last Updated :
16 Dec, 2022
Given a number N, the task is to check if the xor value of the frequency of the digits is zero or not.
Examples:
Input: N = 122233
Output: Yes
Frequencies of 1, 2 and 3 are 1, 3, 2 respectively.
And Xor of 1, 3 and 2 is 0.
Input: N = 123
Output: No
Approach: Count the frequency of all the digits and then iterate over all frequency and xor them if the answer is zero then print Yes else No.
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>
using namespace std;
bool check( int s)
{
int freq[10] = {0},r;
while (s != 0)
{
r = s % 10;
s = int (s / 10);
freq[r] += 1;
}
int xor__ = 0;
for ( int i=0;i<10;i++)
{
xor__ = xor__ ^ freq[i];
if (xor__ == 0)
return true ;
else
return false ;
}
}
int main()
{
int s = 122233;
if (check(s))
cout<< "Yes" <<endl;
else
cout<< "No" <<endl;
}
|
Java
import java.io.*;
class GFG
{
static boolean check( int s)
{
int [] freq = new int [ 10 ];
int r,i;
for (i= 0 ;i< 10 ;i++)
{
freq[i]= 0 ;
}
while (s != 0 )
{
r = s % 10 ;
s = ( int )(s / 10 );
freq[r] += 1 ;
}
int xor__ = 0 ;
for ( i= 0 ;i< 10 ;i++)
{
xor__ = xor__ ^ freq[i];
if (xor__ == 0 )
return true ;
else
return false ;
}
return true ;
}
public static void main(String[] args) {
int s = 122233 ;
if (check(s))
System.out.println( "Yes\n" );
else
System.out.println( "No\n" );
}
}
|
Python3
def check(s):
freq = [ 0 ] * 10
while (s ! = 0 ):
r = s % 10
s = s / / 10
freq[r] + = 1
xor = 0
for i in range ( 10 ):
xor = xor ^ freq[i]
if (xor = = 0 ):
return True
else :
return False
s = 122233
if (check(s)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG
{
static bool check( int s)
{
int [] freq = new int [10];
int r, i;
for (i = 0; i < 10; i++)
{
freq[i]= 0;
}
while (s != 0)
{
r = s % 10;
s = ( int )(s / 10);
freq[r] += 1;
}
int xor__ = 0;
for ( i = 0; i < 10; i++)
{
xor__ = xor__ ^ freq[i];
if (xor__ == 0)
return true ;
else
return false ;
}
return true ;
}
public static void Main()
{
int s = 122233;
if (check(s))
Console.Write( "Yes\n" );
else
Console.Write( "No\n" );
}
}
|
PHP
<?php
function check( $s )
{
$freq = array_fill (0,10,0);
while ( $s != 0)
{
$r = $s % 10;
$s = (int)( $s /10);
$freq [ $r ]+= 1;
}
$xor = 0;
for ( $i =0; $i <10; $i ++)
$xor = $xor ^ $freq [ $i ];
if ( $xor == 0)
return true;
else
return false;
}
$s = 122233;
if (check( $s ))
print ( "Yes" );
else
print ( "No" );
?>
|
Javascript
<script>
function check(s)
{
let freq = new Array(10).fill(0), r;
while (s != 0)
{
r = s % 10;
s = parseInt(s / 10);
freq[r] += 1;
}
let xor__ = 0;
for (let i=0;i<10;i++)
{
xor__ = xor__ ^ freq[i];
if (xor__ == 0)
return true ;
else
return false ;
}
}
let s = 122233;
if (check(s))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(|s|), Auxiliary Space: O(10)
Share your thoughts in the comments
Please Login to comment...