Created
June 1, 2020 08:53
-
-
Save kolharsam/075535080119d65c57dc7dfba2b136b4 to your computer and use it in GitHub Desktop.
Cassidy's Interview Question - 31/5/20
This file contains hidden or 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
;; 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