forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberOccurringOddTimes.java
More file actions
34 lines (29 loc) · 850 Bytes
/
NumberOccurringOddTimes.java
File metadata and controls
34 lines (29 loc) · 850 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.rampatra.arrays;
/**
* Created by IntelliJ IDEA.
*
* @author rampatra
* @since 5/20/15
* @time: 11:09 PM
*/
import com.rampatra.bits.TwoNonRepeatingElements;
/**
* Given an array of positive integers. All numbers occur
* even number of times except one number which occurs odd
* number of times. Find the number in O(n) time & constant space.
* <p>
* See {@link TwoNonRepeatingElements} for a more
* complex problem which is solved in a similar approach.
*/
public class NumberOccurringOddTimes {
public static int numberOccurringOddTimes(int a[]) {
int res = a[0];
for (int i = 1; i < a.length; i++) {
res ^= a[i];
}
return res;
}
public static void main(String[] args) {
System.out.print(numberOccurringOddTimes(new int[]{2, 3, 3, 3, 1, 2, 1}));
}
}