Skip to content

Instantly share code, notes, and snippets.

@SneakyPeet
Last active March 26, 2019 14:54
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 SneakyPeet/f80ad363534a1c79367a93d03103796c to your computer and use it in GitHub Desktop.
Save SneakyPeet/f80ad363534a1c79367a93d03103796c to your computer and use it in GitHub Desktop.
List Of Digits
;;; https://purelyfunctional.tv/issues/purelyfunctional-tv-newsletter-319-tip-shebang-scripting-with-the-clojure-cli/?__s=qn1vfepzj2qsgce6ughs
(defn number-of-digits
"Calculates the number of digits in an integer"
[n]
(int (Math/ceil (Math/log10 (inc n)))))
(defn get-nth-digit
"Gets the nth digit (zero based) from integer x"
[n x]
(int (mod (/ x (Math/pow 10 n)) 10)))
;; fails for zeros
(defn digits [x]
(let [n (dec (number-of-digits x))
k (get-nth-digit n x)
r (Math/pow 10 n)]
(when (>= n 0)
(lazy-seq
(cons k (digits (mod x r)))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment