C Program to find the Number of times when XOR s equal to Sum between 1 and n - HackerRank



// Program by Akash Tripathi (@proakash256) 
 
// To find the Number of times when XOR
// is equal to Sum between 1 and n.

// XOR is binary addition without the
// carry over. For every 0 bit of n
// we can add 1 or 0 without getting a carry,
// and for every 1 bit of n we can add only 0
// without getting a carry, which implies
// XOR = Sum.

// So we calculate the Number of 0's in n
// (upto the Most Significant Bit)
// and raise it to the power 2 to get the
// required answer.

#include <stdio.h>
int main()
{
    int n;
    printf("Enter the Number : ");
    scanf("%d" , &n);
    long c = 0;

    // To Calculate the Number of Zeroes
    while (n > 0)
    {
        if ((n & 1) == 0)
        {
            c = c + 1;
        }
        n = n >> 1;
    }
    c = 1L << c// Same as pow(2 , c)
    printf("\nThe Number of times b/w
            1 and %d when XOR equals
            SUM is %li." , n , c);
    return 0;
}

Comments