It just so happens I remember the thought process I went through.
1. First state the problem: the problem is that we need to treat 0 as a special case, but can't do so because we aren't allowed to use if (and I'm not going to use ternary if as a way round that).
2. First approach: if 0 is problematic, ensure that we never have a length 0 string - by adding a dummy character front and end, and removing them after the operation. Unfortunately this leaves us with the same problem in a different way - if we do this for a zero-length string we end up with a zero-length string which we then want to remove the first and last characters from - no good.
3. Right, so for any solution we need to be able to distinguish between zero and non-zero. The easiest way to do this using the constraints we have is to come up with an expression that evaluates to 0 for an input of 0 and 1 for any positive integer input.
4. x / x + 1 looks positive - 0 divided by anything will always be 0, and we divide by x + 1 to avoid the risk of dividing by zero. Unfortunately it doesn't work, because we always round down.
5. x / x + 1 gives us 1/2, 2/3 and other numbers tending towards (but never reaching) 1, which all get rounded down to 0. We want to round to 1. Doubling this value will always give us a range from 1 to not-quite-2, which is exactly what we want.
6. Looking at the errors we were getting before, we need to add 1 if text.length() is zero in one case and subtract it in the other case. So whip up a formula that maps 0 to +1 and 1 to 0, and add or subtract it accordingly.
7. Simplify the expression.