As luck would have it, an interesting example of a answer with minimal explanation has just been posted.
I was looking for questions that might be asked in a technical interview and I found this one:
Write a function that determines if two integers are equal without using any comparative operators.
public static boolean equal(int a, int b){
Integer first = a;
Integer sec = b;
return (first.toString()).equals(sec.toString());
}
Observation: this isn't such a good question for Code Review, since the artificial restriction makes it more of a Programming Puzzle. One could argue that it violates the "Do you want this to be good code?" rule, and may therefore be off-topic. But that would be a separate Meta question.
This function doesn't use any of comparative operators:
public static boolean equal(int x, int y) {
try {
int r = 1/(x - y);
} catch (RuntimeException e) {
return true;
}
return false;
}
The current score is +1/-4, and an "insufficient justification" moderator notice has been attached to it.
If we go strictly by the rules, this solution would need to be accompanied by an explanation such as:
As others have said, your solution uses String.equals()
, which arguably is a comparison operator (or uses one behind the scenes). Here is a function that doesn't use any comparison operators. Instead of testing x == y
, we can detect whether x - y == 0
by seeing whether it triggers a division by zero error.
Would that explanation add any value? I think that "Behold!" would work just as well. Therefore, I think that in this case, the downvotes and the moderator notice are unjustified.
+ 1 - 1
making the code clearer? Should one comment it? It's insane. \$\endgroup\$