Monday, 25 December 2017

Reverse of a binary number : C program : CHANGE THE EVEN Hacker rank solution in C

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


 int inv(int n) {
    int rev = 0,r;
    while(n > 0) {
        r=n&1;
        rev = rev<<1 | r;
        n =n>> 1;
    }
    return rev;
}

int main()
{
    unsigned int t, i, num;
    scanf("%u", &t);
    for (i = 0; i < t;i++) {
        scanf("%u", &num);
        if (num%2 != 0) {
            printf("%u\n", num);
        } else {
            printf("%u\n", inv(num));
        }
    }
    return 0;
}

Explanation:

 int inv(int n) {
    int rev = 0,r;
    while(n > 0) {
        r=n&1;
        rev = rev<<1 | r;
        n =n>> 1;
    }
    return rev;
}

=========================
The above function is analogous to reverse of decimal number function below

 int inv(int n) {
    int rev = 0,r;
    while(n > 0) {
        r=n%10;
        rev = rev*10+ r;
        n =n/10;
    }
    return rev;
}

=============================

Here to extract last bit (LSB) using
n&1
It will only extract the last bit----
Since the base of binary system is 2 we multiply by using left shift operator as follows

rev<<1 is same as rev*2

Similarly division by 10 is replaced by division by2 which is performed using right shift operator as 
n=n>>1

No comments:

Post a Comment