Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Cassidy's Interview Question - 31/5/20
;; Just wanted to take a different approach to using
;; logarithms or recursively dividing...
;; powers of 2, in binary, have only 1 bit as "1", so I'll look for just that!
(require '[clojure.string :as str])
(defn is-power-of-2?
"Returns true if n is a power of 2"
[n]
(let [bin-str (Integer/toBinaryString n)
count-1s (count (filter #(= "1" %) (str/split bin-str #"")))]
(if (= count-1s 1)
(println "IT IS A POWER OF 2!")
(println "IT IS A POWER OF SOME OTHER NUMBER *(Maybe)"))))
(is-power-of-2? 40)
(is-power-of-2? 64)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment