maximum bitwise AND less than K - rFronteddu/general_wiki GitHub Wiki

Find the maximum bitwise AND less than K for any pair (i, j) with 1 ≤ i < j ≤ N.

  • (K - 1) is the best possible value less than K.
  • We check if there exist two numbers a and b (≤ N) whose bitwise AND equals K - 1.
  • That’s true if we can “fill” the bits of K - 1 up to K using numbers ≤ N.
  • (K - 1) | K is the smallest number that must be ≤ N for that to be possible.
    public static int bitwiseAnd(int N, int K) {
    // Write your code here
        int max = 0;
        for(int i = N; i > 0; i--) {
           for(int j = N - 1; j > 0; j--) {
                if(i != j && (i&j) < K) {
                    max = Math.max(i&j, max);
                }
           }
        }
        return max;
    }