Hackerrank Flipping bits
Challenge
Prit’s solution
(defn flipping-bits [n]
"TOC: <1h
Complexity: O(1), since bounded by the 32 bit limit"
(let [bin-seq (seq (Long/toBinaryString n)) ;; looked up toBinaryString online
size (count bin-seq)
padded-bin-seq (concat (repeat (- 32 size) \0) bin-seq)]
(loop [padded-bin-seq padded-bin-seq flipped-val 0]
(if (empty? padded-bin-seq)
flipped-val
(recur (rest padded-bin-seq)
(+ flipped-val
(if (= (first padded-bin-seq) \0)
(reduce * (repeat (dec (count padded-bin-seq)) 2))
0)))))))
(flipping-bits 4294967295)
I first convert the integer to a bit-string using Long/toBinaryString and create a sequence. Then I pad the sequence with most significant zeros to make the sequence 32 in length.
Then I loop through the sequence and add to the value, which is initialized at 0, 2^n if the sequence element is \0 and 0 otherwise, where n is the position of the bit the sequence where the least significant bit has the position 0.