Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal to Binary Clojure

Tags:

clojure

I'm following this pseudo code to convert decimal to binary recursively.

findBinary(decimal)
   if (decimal == 0)
      binary = 0
   else
      binary = decimal % 2 + 10 * (findBinary(decimal / 2)

This is what I have tried:

(defn binary [n]
  (loop [res 0]
    (if (= n 0)
    res
    (recur (res (* (+ (mod n 2) 10) (binary (quot n 2)))) )
    )
  )
)

But I get this error :

ClassCastException java.lang.Long cannot be cast to clojure.lang.IFn  user/binary (form-init9002795692676588773.clj:6)

Any ideas how to fix the code to complete the task?

like image 284
AMM Avatar asked Jun 12 '26 23:06

AMM


1 Answers

I realize, that this is about the journey and not the result. But to have it mentioned: Long/toString can give you a string from a number with a wide variety of radixes.

(Long/toString 123 2)
; → "1111011"
like image 77
cfrick Avatar answered Jun 18 '26 00:06

cfrick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!