Time spent here:

Tuesday, 15 December 2015

AND product

Problem Statement
You will be given two integers A and B. You are required to compute the bitwise AND amongst all natural numbers lying between A and B, both inclusive.
Input Format
First line of the input contains T, the number of testcases to follow. 
Each testcase in a newline contains A and B separated by a single space.
Constraints
1T200 
0AB<232
Output Format
Output one line per test case with the required bitwise AND.
Sample Input
3 
12 15 
2 3 
8 13
Sample Output
12 
2 
8
Explanation
For the first testcase,
12 & 13 & 14 & 15 = 12

solution:

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {

    long int t,a,b,i;
    scanf("%ld",&t);
    while(t--)
    {
       scanf("%ld %ld",&a,&b);
        if(a%2==0)
            i=a+2;
        else
            i=a+1;
        for(;i<b;i=i+2)
            a=a&i;
        printf("%ld\n",a);    
    }
    return 0;
}

1 comment:

  1. Optimized Code (Tested on Hackerrank)

    #include
    #include
    #include
    #include
    #include
    using namespace std;

    int main() {
    int nTestCases;
    unsigned int nStart, nEnd;

    scanf("%d", &nTestCases);

    while (nTestCases--)
    {
    scanf("%u %u", &nStart, &nEnd);
    unsigned int nWalk = (nEnd - nStart);
    unsigned int nMask = 1;
    while (nWalk)
    {
    nWalk >>= 1;
    nMask <<= 1;
    }
    nMask = nMask - 1;

    printf("%u\n", (nStart & ~nMask & nEnd));
    }
    return 0;
    }

    ReplyDelete