Uiua, 24 bytes
⨬⍜(-1°⊂⇌base3|⊙↘⟜ ̄¬)0⊸<2
Try it: Uiua pad. The comment # Experimental! enables the experimental base function, which has not yet been stabilized.
Explanation: A very elegant use of the ⍜ under modifier, which applies a transformation function, then applies a second function to modify the result, and undoes (applies the inverse function of) the transformation.
Here, the transformation is -1°⊂⇌base3: Convert to base 3, separate the first digit from the rest, and subtract 1 from that digit.
Subtracting 1 from the digit gives either 0 or 1. This means that changing the 1 to a 2 and vice versa is as simple as applying ¬ (boolean NOT). We then use this opposite boolean as the number of digits to remove from the end of the list: ⊙↘⟜ ̄.
The transformation is undone: Add 1 to the inverted boolean, prepend it back to the array of digits, and convert back from base 3.
This does the task, but it fails for the numbers zero and one, since for zero you can't take the first digit from the empty list returned by base3, and for one the result is incorrect because we drop 1 from the end and flip the 1 to a 2, rather than flipping first and then dropping. Therefore, I wrapped the whole thing with ⨬F0⊸<2, which does the logic if the number is greater than 2, or returns zero otherwise.
- 12.6k
- 1
- 31
- 90