Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@logbasex
Last active June 5, 2020 18:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save logbasex/616463a7f1a83e7f8f36919e7ab2f74f to your computer and use it in GitHub Desktop.
Save logbasex/616463a7f1a83e7f8f36919e7ab2f74f to your computer and use it in GitHub Desktop.
This solution implement by bitwise operator.
package com.algorithm.bitwise;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class FindLargestElementV2 {
//MSB: most significant bit.
public static long countGreaterOrEqualElementWithSameMSB(List<Integer> seq, int valueAtMSBIndex) {
return seq.stream().filter(element -> (valueAtMSBIndex & element) == valueAtMSBIndex).count();
}
public static void main(String[] args) {
List<Integer> initialSeq = Stream.concat(Stream.of(1, 5, 9, 30, 15), Stream.of(Integer.MAX_VALUE))
.collect(Collectors.toList());
AtomicInteger max = new AtomicInteger();
Stream.iterate(31, i -> i - 1).limit(32).forEachOrdered(bitIndex -> {
int bitCheck = max.get() | 1 << bitIndex;
long count = countGreaterOrEqualElementWithSameMSB(initialSeq, bitCheck);
if (count > 1) {
max.set(bitCheck);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment