Monday 14 October 2019

Given 2 integers a,k. Find if kth bit is set or not using bitwise right shift operator

//Given 2 integers a,k. Find if kth bit is set or not using bitwise right shift operator
#include<stdio.h>

int main() {
    int a,k,t;
    scanf("%d%d",&a,&k);
    t=a>>(k-1);
    if(t&1 == 0)
        printf("%d th bit is not set",k);
    else
        printf("%dth bit is set",k);
}

Check whether 3 numbers are equal or not using bitwise operators

//Given 3 integers a,b,c. Find if all the 3 numbers are same or not using bitwise operators
#include<stdio.h>

int main() {
    int a,b,c,t;
    scanf("%d%d%d",&a,&b,&c);
    t=(a^b)|(b^c);
    if(t==0)
        printf("same");
    else
        printf("not same");
}

You are given two integers a and b. You need to find number of digits in element a (let us call it n) and print out maximum number obtained by doing xor of 10^n and k, where k lies from 1 to b

//You are given two integers a and b. You need to find number of digits in element a (let us call it n) and print out maximum number obtained by doing xor of 10^n and k, where k lies from 1 to b
#include<stdio.h>
#include<math.h>
int main() {
    int a,b,n=0,k,max=0,temp,t,i,c=0;
    scanf("%d%d",&a,&b);
    //n=log(a)+1;
    t=a;
    while(t)
    {
        n++;
        t=t/10;
    }
    //printf("number of digits=%d\n",n);
    t=1;
    for(i=1;i<=n;i++)
        t=t*10;
    //printf("10 to power of n=%d\n",t);
    for(k=1;k<=b;k++)
    {
       
        temp=t^k;
        if(max<temp)
            max=temp;
    }
    printf("%d",max);
}