Skip to content

Instantly share code, notes, and snippets.

@kolharsam
Created June 1, 2020 08:53
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 kolharsam/075535080119d65c57dc7dfba2b136b4 to your computer and use it in GitHub Desktop.
Save kolharsam/075535080119d65c57dc7dfba2b136b4 to your computer and use it in GitHub Desktop.
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