Functional algorithm for changing the number

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))))) 

Here's what I should call it (reverse-number 123 0) , and the expected result: 321 . When I run this, the REPL just hangs .

Can someone please explain to me what is going on, what I did wrong and how to make this function work?

Note I know that I can use string functions to change the number. In fact, I have already done this, but I am not interested in this. All I want to do is jump into functional languages. Therefore, I am trying to use several approaches.

Using string functions :

 (defn reverse-number [n] (Integer. (clojure.string/reverse (str n)))) (reverse-number 123) ; --> 321 

I don't like this version because it looks like cheating using a lowercase version of the reverse.

+4
source share
1 answer

You should use quot instead of / .

/ in clojure will give you a share, so number will never be 0 (unless it is 0 from the very beginning), and quot will give you "integer division".

Examples:

 user=> (/ 123 10) 123/10 user=> (quot 123 10) 12 
+5
source

All Articles