>Can someone tell me how I can take an integer, reverse its digits, and then use
>it as an argument to a function which requires a numeric argument? The function
>which does the reversal should be efficient as it will have to work with
>arbitrarily large integers. I tried converting the integer using the pack
>function (explode) and was then able to use reverse but getting the result back
>to an integer has so far eluded me.
Ira, how about using a function like the one below, which reverses
the digits without creating any intermediate strings? (It does build
a list though!).
John
----
(defun REV-DIGITS (n &optional (base 10))
;; First create list of digits in "n"
(let (digits)
(loop
(multiple-value-bind (quot rem) (truncate n base)
(push rem digits)
(if (zerop quot)
(return)
(setq n quot))))
;; Now build the "reversed" integer
(let ((pow 1) (result 0))
(dolist (d digits result)
(setq result (+ result (* d pow)))
(setq pow (* pow base))))))
In article <··········@infa.central.susx.ac.uk> ·····@cogs.susx.ac.uk
(John Williams) writes:
> Ira, how about using a function like the one below, which reverses
> the digits without creating any intermediate strings? (It does build
> a list though!).
Obviously, the creation of the intermediate list is superfluous:
(defun reverse-integer (n &optional (base 10))
(do ((last-digit) (but-last-digits n) (result 0))
((= but-last-digits 0) result)
(multiple-value-setq (but-last-digits last-digit)
(floor but-last-digits base))
(setf result (+ (* base result) last-digit))))
--
Stephan Kepser ······@cis.uni-muenchen.de
CIS Centrum fuer Informations- und Sprachverarbeitung
LMU Muenchen, Wagmuellerstr. 23/III, D-80538 Muenchen, Germany
Tel: +49 +89/2110666 Fax: +49 +89/2110674