Last active
June 5, 2020 18:25
-
-
Save logbasex/616463a7f1a83e7f8f36919e7ab2f74f to your computer and use it in GitHub Desktop.
This solution implement by bitwise operator.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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