
C++ Coding Practice #2
Today's C++ coding practice is to check if two numbers are equal without using arithmetic operators or comparison operators.
The Code
Here's the implementation I whipped out in under 5 minutes:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
bool IsEqual(int a, int b) { | |
// a b xor | |
// 0 0 0 (equal) | |
// 0 1 1 | |
// 1 0 1 | |
// 1 1 0 (equal) | |
return (a^b) == false; | |
} | |
std::string ToString(bool b) { | |
return b ? "True" : "False"; | |
} | |
int main() { | |
int a = 4; | |
int b = 3; | |
std::cout << a << " == " << b << " (" << ToString(IsEqual(a, b)) << ")" << std::endl; | |
a = 7; | |
b = 7; | |
std::cout << a << " == " << b << " (" << ToString(IsEqual(a, b)) << ")" << std::endl; | |
return 0; | |
} |
You can compile and run this code with the following commandline:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ g++ test.cpp && ./a.out | |
4 == 3 (False) | |
7 == 7 (True) |
Dev Notes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Whenever there is a constraint to not use arithmetic operators | |
// in a calculation, I immediately always think of the bitwise | |
// operators. | |
// | |
// As shown in the code, the XOR operator ("exclusive OR") is the | |
// right candidate for the job because it has these properties: | |
// | |
// a b xor | |
// --------------- | |
// 0 0 0 (equal) | |
// 0 1 1 | |
// 1 0 1 | |
// 1 1 0 (equal) |