mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-07 17:56:02 +08:00
Add NumberAppearingOddTimes algorithm (#5633)
This commit is contained in:

committed by
GitHub

parent
f3b2a94e74
commit
b54cc21ade
@ -0,0 +1,21 @@
|
||||
package com.thealgorithms.bitmanipulation;
|
||||
|
||||
/**
|
||||
* Find the Number Appearing Odd Times in an array
|
||||
* @author Lakshyajeet Singh Goyal (https://github.com/DarkMatter-999)
|
||||
*/
|
||||
|
||||
public final class NumberAppearingOddTimes {
|
||||
private NumberAppearingOddTimes() {
|
||||
}
|
||||
public static int findOddOccurrence(int[] arr) {
|
||||
int result = 0;
|
||||
|
||||
// XOR all elements in the array
|
||||
for (int num : arr) {
|
||||
result ^= num;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
package com.thealgorithms.bitmanipulation;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class NumberAppearingOddTimesTest {
|
||||
|
||||
@Test
|
||||
void testFindOddOccurrence() {
|
||||
int[] arr1 = {5, 6, 7, 8};
|
||||
assertEquals(12, NumberAppearingOddTimes.findOddOccurrence(arr1));
|
||||
|
||||
int[] arr2 = {2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2};
|
||||
assertEquals(5, NumberAppearingOddTimes.findOddOccurrence(arr2));
|
||||
|
||||
int[] arr3 = {10, 10, 20, 20, 30};
|
||||
assertEquals(30, NumberAppearingOddTimes.findOddOccurrence(arr3));
|
||||
|
||||
int[] arr4 = {-5, -5, -3, -3, -7, -7, -7};
|
||||
assertEquals(-7, NumberAppearingOddTimes.findOddOccurrence(arr4));
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user