শনিবার, ৪ নভেম্বর, ২০১৭

UVA 12898 - And Or

Explaintion:
Step 1: Count bit length of a and b
step 2: if lenb>lena then OR = 2^lenb - 1 and And = 0*/
step 3: find/count not change bits between a and b, from MSB to LSB
        Or = b | R
         And = b | ~R  where R contain's 1 (total 1 = count)

Example:
[1]a = 7  b = 8

lena = 3 , Lenb = 4

 so Or = 2^lenb - 1 = 16 - 1 = 15

And = 0

[2] Let a = 12 , b =15

lena = 4, len b = 4
a = 1100 , b = 1111

start j = 3 and break when j = 1

R = 1LL<<(j+1) - 1 = (11)2
unchanged first 2 bits
Or = b | R = (1111) = 15
And = b & ~R = (1100) = 12

Source Code:
#include<bits/stdc++.h>
using namespace std;
#define maxlen 61
typedef long long ll;
int main()
{
    int n,c,i,lena,lenb,j;
    int a1[maxlen],b1[maxlen];
    ll Or,And,x,a,b,R;
    const ll one = 1;
    scanf("%d",&n);
    for(i = 1; i <= n; i++)
    {
        scanf("%lld %lld",&a,&b);
        /*Step 1: Count bit length of a and b*/
        c = 0;
        x = a;
        while(x)
        {
            a1[c] = x&1;
            x >>= 1;
            c++;
        }
        lena = c;
        c = 0;
        x = b;
        while(x)
        {
            b1[c] = x&1;
            x >>= 1;
            c++;
        }
        lenb = c;
        /*step 2: if lenb>lena then OR = 2^lenb - 1 and And = 0*/
        /*step 3: find/count not change bits between a and b, from LSB to MSB
                  Or = b | R and And = b | ~R  where R contain's 1 (total 1 = count)
         */
        if(lenb>lena)
        {
            Or =(one<<lenb)-1;
            And = 0;
        }
        else
        {
            for( j = lenb-1; j >= 0; j--)
            {
                if(a1[j]!=b1[j]) break;
            }
            R = (one<<(j+1))-1;
            Or = b|R;
            And = b&~R;
        }
        printf("Case %d: %lld %lld\n",i,Or,And);
    }
    return 0;
}

কোন মন্তব্য নেই:

একটি মন্তব্য পোস্ট করুন

Factorization with prime Sieve

vector <int> prime; char sieve[1000009]; int N=1000009; void primeSieve ( ) { sieve[0] = sieve[1] = 1; prime.push_back(2); ...