> I have a variable that contains a bunch of numbers:
or rather you have variable containg a result tree fragment
corresponding to a root node with child a text node
with string value consisting of digits and spaces.
You've given no context to your real problem but the solution may well
be not to start from here but to generate a different initial structure.
> I want the last number fast, i.e., I want it in constant time, not
> O(n), where n is the length of the list of numbers.
even getting the length of a literal string might (depending on
processor optimisations) take time proportional to the length of the
string. A processor may use an optimsed string representation that lets
it know there are no surrogate pairs (if it it using utf16 internally) or
it may not, but if it doesn't, then doing more or less any operation has
complexity at least O(n).
Hwever assuming you can get the length of the string in negligable time
then you can get the last number in time proportional to the number of
digits in that number by starting with
substring($numbers,string-length($numbers))
to get the last character, and then backing up until you get the first
non digit and re-assembling the final number.
David