Skip to content

Instantly share code, notes, and snippets.

@tonygaetani
Last active November 13, 2015 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonygaetani/cf7ad7a03448bc8d6d5c to your computer and use it in GitHub Desktop.
Save tonygaetani/cf7ad7a03448bc8d6d5c to your computer and use it in GitHub Desktop.
(defn pow2 [n]
"Returns a long representing 2^n"
(->> n (Math/pow 2) long))
(defn b10->b2
"Converts a base 10 number to a lazy seq of 1's and 0's that make up a base 2 number"
([n] (b10->b2 n '()))
([n col]
(if (= 1 n)
(merge col 1) ; base case
(let [r (mod n 2)]
(b10->b2 (->> (/ n 2) Math/floor long) (merge col r))))))
(defn b2->b10 [col]
"Converts a seq of 1's and 0's that make up a base 2 number into a base 10 number"
(when (seq col)
(reduce + (map #(if (zero? (second %)) 0 (pow2 (first %))) (map-indexed vector (reverse col))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment