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:

#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;
}
view raw test.cpp hosted with ❤ by GitHub

You can compile and run this code with the following commandline:

$ g++ test.cpp && ./a.out
4 == 3 (False)
7 == 7 (True)
view raw commandline.txt hosted with ❤ by GitHub

Dev Notes

//
// 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)
view raw dev-notes.cpp hosted with ❤ by GitHub

Explore More