715966. Geekina Hate 1s
Hard
Geekina Hate 1s
Summary
The problem is about finding all numbers in a given array that have an odd number of 1's in their binary representation. This requires a combination of binary search and bit manipulation techniques.
Detailed Explanation
The key to this problem is understanding how to efficiently count the number of 1's in each number's binary representation. This can be done using bitwise operations, specifically the XOR operator (^). We'll use this technique to create a function that counts the number of 1's in a given integer.
Here's the step-by-step solution:
- Initialize an empty list
resultto store the numbers with an odd number of 1's. - Iterate through each number
numin the input array. - Use bitwise operations to count the number of 1's in
num. This can be done by XORingnumwith itself, effectively canceling out all the bits that are not set (i.e., 0).
import java.util.*;
public class GeekinaHate1s {
public static List<Integer> geekinaHate1s(int[] arr) {
List<Integer> result = new ArrayList<>();
for (int num : arr) {
int count = 0;
num ^= num;
while (num) {
if ((num & 1) == 1) {
num >>= 1;
} else {
break;
}
}
if (count % 2 != 0) {
result.add(num);
}
}
return result;
}
}