Can mathematical operators *, /, +, -, ^ be used to convert a non-zero number to 1?
Use the expression n/n^0
.
If n
is not zero:
Step Explanation
------- -------------------------------------------------------------------------------
n/n^0 Original expression.
1^0 Any number divided by itself equals 1. Therefore n/n becomes 1.
1 1 xor 0 equals 1.
If n
is zero:
Step Explanation
------- -------------------------------------------------------------------------------
n/n^0 Original expression.
0/0^0 Since n is 0, n/n is 0/0.
NaN^0 Zero divided by zero is mathematically undefined. Therefore 0/0 becomes NaN.
0^0 In JavaScript, before any bitwise operation occurs, both operands are normalized.
This means NaN becomes 0.
0 0 xor 0 equals 0.
As you can see, all non-zero values get converted to 1, and 0 stays at 0. This leverages the fact that in JavaScript, NaN^0
is 0.
Demo:
[0, 1, 19575, -1].forEach(n => console.log(`${n} becomes ${n/n^0}.`))
c / (c + 5e-324)
should work. (The constant 5e-324
is Number.MIN_VALUE
, the smallest representable positive number.) If x is 0, that is exactly 0, and if x is nonzero (technically, if x is at least 4.45014771701440252e-308, which the smallest non-zero number allowed in the question, 0.01, is), JavaScript's floating-point math is too imprecise for the answer to be different than 1, so it will come out as exactly 1.
(((c/c)^c) - c) * (((c/c)^c) - c)
will always return 1 for negatives and positives and 0 for 0.
It is definitely more confusing than the chosen answer and longer. However, I feel like it is less hacky and not relying on constants.
EDIT: As @JosephSible mentions, a more compact version of mine and @CRice's version which does not use constants is:
c/c^c-c