Posts

Search

Day 29: Bitwise AND

Objective
Welcome to the last day! Today, we're discussing bitwise operations. Check out the Tutorial tab for learning materials and an instructional video!
Task
Given set . Find two integers,  and  (where ), from set  such that the value of  is the maximum possible and also less than a given integer, . In this case,  represents the bitwise AND operator.
Input Format
The first line contains an integer, , the number of test cases.
Each of the  subsequent lines defines a test case as  space-separated integers,  and , respectively.
Constraints
Output Format
For each test case, print the maximum possible value of  on a new line.
Sample Input
3
5 2
8 5
2 2
Sample Output
1
4
0
Explanation

All possible values of  and  are:
The maximum possible value of  that is also  is , so we print  on a new line.

Solution :
#include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() 
{
    int T, n, k, i, j, val;
    scanf("%d",&T);
    while (T > 0) 
    {
        int maximum = 0;
        scanf("%d%d",&n, &k);
        int max_val = 0;
        int a = 0, b = k - 1;
    
    for (a = n; a > 2; a--) 
    {
        if (a == b)
            continue;
        if ((a & b) > max_val) 
        {
            max_val = a & b;
        }
    }
    
    printf("%d\n",max_val );
    
    T--;
  }
  return 0;
}