Created
July 6, 2013 10:06
-
-
Save siscia/5939462 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns base-conversion.core) | |
(def characters | |
(concat (map char (range 48 58)) (map char (range 65 91)))) | |
(def conversion-table | |
(zipmap | |
characters | |
(range))) | |
(defn base-n-to-base-10 | |
[^String string ^Integer base] | |
(let [string (clojure.string/upper-case string)] | |
(assert (every? #(< (conversion-table %) base) string)) | |
(loop [num string | |
acc 0] | |
(if (seq num) | |
(recur (drop 1 num) (+ (* base acc) (get conversion-table (first num)))) | |
acc)))) | |
(defn base-10-to-base-n | |
[^Integer number ^Integer base] | |
(loop [num number | |
acc []] | |
(if (zero? num) | |
(clojure.string/join (reverse acc)) | |
(recur (int (/ num base)) | |
(conj acc (nth characters (mod num base))))))) |
@rkneufeld, Oh yes, I knew that, but how you said it was just an exercise...
Actually integer/parseInt is implemented pretty much like my function.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Cool exercise. I just wanted to poke in and make sure you knew Integer/parseInt and Integer/toString both take an optional radix number (base) if you're doing this for real out in the wild.