Longest AND Subarray Codechef Solution|Problem Code: ANDSUBAR

Hello coders, today we are going to solve Longest AND Subarray Codechef Solution|Problem Code: ANDSUBAR.

Longest AND Subarray Codechef Solution
Longest AND Subarray Codechef Solution

Problem

You are given an integer N. Consider the sequence containing the integers 1,2,…,N in increasing order (each exactly once). Find the length of the longest subarray in this sequence such that the bitwise AND of all elements in the subarray is positive.

Input Format

  • The first line contains T denoting the number of test cases. Then the test cases follow.
  • Each test case contains a single integer NN on a single line.

Output Format

For each test case, output on a single line the length of the longest subarray that satisfy the given property.

Constraints

  • 1≤T≤1051≤T≤105
  • 1≤N≤1091≤N≤109

Subtasks

  • Subtask 1 (100 points): Original constraints

Sample Input 1 

5
1
2
3
4
7

Sample Output 1 

1
1
2
2
4

Longest AND Subarray CodeChef Solution in JAVA

import java.util.Scanner;
public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int T = sc.nextInt();
    for (int tc = 0; tc < T; ++tc) {
      int N = sc.nextInt();
      System.out.println(solve(N));
    }
    sc.close();
  }
  static int solve(int N) {
    int result = 0;
    for (long i = 1; i <= N; i <<= 1) {
      result = Math.max(result, (int) Math.min(i, N + 1 - i));
    }
    return result;
  }
}

Disclaimer: The above Problem (Longest AND Subarray) is generated by CodeChef but the solution is provided by Chase2learn.This tutorial is only for Educational and Learning purpose.

Sharing Is Caring