I've been playing with Clojure lately and I can't get this algorithm to work:
(defn reverse-number [number reversed]
(if (= number 0)
reversed
(reverse-number (/ number 10)
(+ (rem number 10) (* reversed 10)))))
This is how I should call it (reverse-number 123 0) and the result I expect is: 321.
When I run this, the REPL just hangs.
Can someone explain me, please, what is happening, what I did wrong and how to get this function working?
Note: I know I can use string functions to reverse a number. Actually, I already did this, but I'm not interested in this solution. All I want is to make the leap to functional languages. That's why I try multiple approaches.
Using string functions:
(defn reverse-number [n]
(Integer. (clojure.string/reverse (str n))))
(reverse-number 123) ; --> 321
I don't like this version since it feels like cheating by using the string version of reverse.
3210be in reverse?123, why? This is the answer I expect. I certainly wouldn't expect0123since that wouldn't be a correct number...