Check if one number is a complement of another:
One’s complement of a number is obtained by inverting all the bits.
Example:
num_1 = 10
num_2 = 5
10 ‘s binary is 1010
10’s one’s complement is 0101
5 binary is 0101.
Hence 10 is one’s complement of 5.
To do this programmatically, we take the XOR of num_1 and num_2 and check if all the bits are set. If all the bits are set, then the result is true else false.
Check if both the numbers are same.
For this we take the XOR of 2 numbers. If the XOR of 2 numbers is 0 then 2 numbers are same.
Solution in C++
/* // xor of two bits is 0 if both the bits are same // otherwise it is 1 0 xor 0 = 0 1 xor 1 = 0 1 xor 0 = 1 0 xor 1 = 1 */ #include<iostream> #include<vector> #include<string> using namespace std; bool all_bits_are_set(int num) { if (((num + 1) & num) == 0) return true; return false; } void check_one_num_complement_of_other(int num_1, int num_2) { if (all_bits_are_set(num_1 ^ num_2)) cout<<num_1 <<" is ones complement of "<<num_2<<endl; else cout<<num_1 <<" is not ones complement of "<<num_2<<endl; } void check_if_both_number_are_same(int num_1, int num_2) { if(num_1 ^ num_2) cout<<num_1 <<" is not equal to "<<num_2<<endl; else cout<<num_1 <<" is equal to "<<num_2<<endl; } int main() { int num_1 = 10; int num_2 = 5; check_one_num_complement_of_other(num_1, num_2); check_if_both_number_are_same(num_1, num_2); num_1 = 10; num_2 = 10; check_one_num_complement_of_other(num_1, num_2); check_if_both_number_are_same(num_1, num_2); return 0; }
Output:
10 is ones complement of 5 10 is not equal to 5 10 is ones complement of 10 10 is equal to 10