Skip to content

Commit 871aa52

Browse files
Added algorithm for Number Appearing Odd Times using Bit Manipulation
1 parent 9fb8192 commit 871aa52

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
/**
4+
* Find the Number Appearing Odd Times in an array
5+
* @author Lakshyajeet Singh Goyal (https://github.com/DarkMatter-999)
6+
*/
7+
8+
public class NumberAppearingOddTimes {
9+
public static int findOddOccurrence(int[] arr) {
10+
int result = 0;
11+
12+
// XOR all elements in the array
13+
for (int num : arr) {
14+
result ^= num;
15+
}
16+
17+
return result;
18+
}
19+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
class NumberAppearingOddTimesTest {
8+
9+
@Test
10+
void testFindOddOccurrence() {
11+
int[] arr1 = {5, 6, 7, 8};
12+
assertEquals(12, NumberAppearingOddTimes.findOddOccurrence(arr1));
13+
14+
int[] arr2 = {2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2};
15+
assertEquals(5, NumberAppearingOddTimes.findOddOccurrence(arr2));
16+
17+
int[] arr3 = {10, 10, 20, 20, 30};
18+
assertEquals(30, NumberAppearingOddTimes.findOddOccurrence(arr3));
19+
20+
int[] arr4 = {-5, -5, -3, -3, -7, -7, -7};
21+
assertEquals(-7, NumberAppearingOddTimes.findOddOccurrence(arr4));
22+
}
23+
}

0 commit comments

Comments
 (0)