Odd number of times: Given an array, find the int that appears an odd number of times. (There will always be only one integer that appears an odd number of times.) code example
Example 1: Given an array of integers, find the one that appears an odd number of times. There will always be only one integer that appears an odd number of times
function findOdd(A) {
var countOccurencesOfInt = 0;
for (let i = 0; i < A.length; i++) {
var currentIterationInt = A[i];
for (let j = 0; j < A.length; j++) {
if (currentIterationInt == A[j]) {
countOccurencesOfInt++;
}
}
if (countOccurencesOfInt % 2 != 0) {
return currentIterationInt;
}
}
}
//or
function findOdd(arr) {
var result, num = 0;
arr = arr.sort();
for (var i = 0; i < arr.length; i++) {
if (arr[i] === arr[i+1]) {
num++;
} else {
num++;
if (num % 2 != 0) {
result = arr[i];
break;
}
}
}
return result;
}
Example 2: If there are an odd number of elements in the array, return the element in the middle of the array.
public String middleElement(String[] array)
{
if (array.length >=1){
if (array.length %2 != 0){
return array[array.length/2];
}
else if(array.length %2 == 0){
return array[array.length/2];
}
return "";
}
else return "";
}