The odd occurrences of the given sequence is nothing but finding the number of times a number is present in the given sequence, if the number occurred odd number of times then the number is said to be occurred odd number of times, else no.
Example:
seq = {1,2,3,4,2,3,4,1,1}
output: 1 occurred odd no.of times
Here, in the above program the number 1 occurred odd no.of times and remaining numbers occurred even no.of times. So, the output is 1.
The source code for the given example is written below
Program:
METHOD - 1
public class Main
{
public static void main(String[] args) {
int array[] = {1,2,3,2,3,1,4,5,3,5,4};
int res=0;
for(int i = 0; i < array.length; i++)
{
res = res^array[i];
}
System.out.println("The number occurred odd no.of times is : "+res);
}
}
Output:
The number occurred odd no.of times is : 3
METHOD - 2
public class Main
{
public static void main(String[] args) {
int array[]={1,2,3,2,3,1,4,5,3,5,4};
for(int i=0;i<array.length;i++)
{
int count=0;
for(int j=0;j<array.length;j++)
{
if(array[i]==array[j])
{
count++;
}
}
if(count%2!=0)
{
System.out.print("The number occurred odd no.of times is:"+array[i]);
break;
}
}
}
}
Output:
The number occurred odd no.of times is : 3

0 Comments