Tuesday, 23 December 2014

Hackerrank AND Product Solution


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
For second testcase,
2 & 3 = 2
For the third testcase,
8 & 9 & 10 & 11 & 12 & 13 = 8

Source Code:

 #include <cmath>  
 #include <cstdio>  
 #include <vector>  
 #include <iostream>  
 #include <algorithm>  
 using namespace std;  
 int main() {  
   /* Enter your code here. Rea input from STDIN. Print output to STDOUT */    
   int t;  
   cin>>t;  
   while(t--){  
     long long x,y,ans;  
     cin>>x>>y;  
     for(long long i=x;i<y;i++){  
       y = y & (x+1);  
       y++;  
     }  
     cout<<x<<endl;}  
   return 0;  
 }  


** The above solution is my own code and it may not be the optimal solution or optimal way to approach the problem but it passes all the testcases in Hackerrank. So if you have any optimal approaches feel free to paste the code as the comment below..... :) :) :)

4 comments:

  1. chutiye nandan galat code hai :/

    ReplyDelete
  2. 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
  3. #include
    #include
    #include
    #include
    #include
    #include
    #include

    int main(){
    unsigned int Q,i,a0,n1,n2;
    scanf("%d",&Q);
    for(a0 = 0; a0 < Q; a0++){
    scanf("%u %u",&n1,&n2);
    unsigned int sum=n1,sum2=n2;
    while(n2>=n1)
    {
    sum=sum&n1;
    sum2=sum2&n2;
    n1++;
    n2--;
    }
    printf("%u\n",sum&sum2);
    }
    return 0;
    }

    ReplyDelete
  4. Nice one..thanks it helped me

    ReplyDelete