XOR of two numbers after making length of their binary representations equal | C ++ implementation to return XOR of two numbers after making length of their binary representation same ; function to count the number of bits in binary representation of an integer ; initialize count ; count till n is non zero ; right shift by 1 i . e , divide by 2 ; function to calculate the xor of two numbers by adding trailing zeros to the number having less number of bits in its binary representation . ; stores the minimum and maximum ; left shift if the number of bits are less in binary representation ; driver code to check the above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int count ( int n ) { int c = 0 ; while ( n ) { c ++ ; n = n >> 1 ; } return c ; } int XOR ( int a , int b ) { int c = min ( a , b ) ; int d = max ( a , b ) ; if ( count ( c ) < count ( d ) ) c = c << ( count ( d ) - count ( c ) ) ; return ( c ^ d ) ; } int main ( ) { int a = 13 , b = 5 ; cout << XOR ( a , b ) ; return 0 ; }